Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use js array forEach

Shulou Source: shulou.com Published: 2022-06-03 00:57:19 10月15日 Update

This article mainly introduces "how to use js array forEach". In daily operation, I believe many people have doubts about how to use js array forEach. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "how to use js array forEach"! Next, please follow the editor to study!

1. ForEach () is similar to map () in that it also acts each element on the incoming function in turn, but does not return a new array.

2. ForEach () is often used to traverse an array, calling each element of the array and passing it to the callback function. The transfer function does not need to return a value.

Example

Var arr=; try {arr.forEach ((item,index) = > {if (item console.log (item)); / / [1,0, Array (4)] the current value function Counter () {this.sum = 0; this.count = 0;} / / because the thisArg parameter (this) is passed to forEach (), which is passed to the callback function as its this value each time it is called. Counter.prototype.add = function (array) {array.forEach (function (entry) {this.sum + = entry; + + this.count;}, this); / / ^-Note}; const obj = new Counter (); obj.add ([2,5,9]); obj.count;// 3 = = (1 + 1 + 1) obj.sum;// 16 = = (2 + 5 + 9)

Every array has this method.

Callback parameters are: each item, index, original array

Array.prototype.forEach = function (fn, thisArg) {var _ this; if (typeof fn! = = "function") {throw "argument must be a function";} if (arguments.length > 1) {_ this = thisArg;} if (! Array.isArray (arr)) {throw "can only use forEach methods on arrays";} for (let index = 0; index < arr.length; index++) {fn.call (_ this, arr [index], index, arr);}} At this point, the study on "how to use js array forEach" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Arrays functions parameters elements methods learning being more knowledge indexing processing help practicality next functions examples articles theories knowledge points articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Apple Microsoft vpn MariaDB