Home >Web Front-end >JS Tutorial >Sharing methods for JavaScript array iteration implementation
This article mainly introduces the JavaScriptarray iteration method, which has a good reference value. Let's take a look at it with the editor
Recently, data processing is often involved in work. Arrays are especially common. They often need to be traversed and converted. Articles on the Internet are scattered here and there, so I have to do it myself. Find the little red book, flip it out, and make a note of it for future inquiries.
Commonly used iteration methods for arrays
ECMAScript5 defines 5 iteration methods for arrays. Each method accepts two arguments: a function fn to be run on each item and (optionally) a scope object to run the function on - affecting the value of `this`.
The function (fn) passed into these methods will receive 3 parameters: item, index, array; such as:
array.forEach(function(item,index,array){ //do your staff here; },this)
Depending on the method of use, the return value of this function after execution , may/may not affect the return value in the method.
The functions and return values of these five iteration methods are summarized as follows:
ECMAScript5 Array element iteration method
Simply put: every(), some() methods are suitable for
conditional judgment on array elements;
filter(), map() The method is suitable for conditional filtering/reprocessing of arrays;
the forEach() method does not operate on the array itself, but only applies it twice to the array elements;
Introduced below The following are examples of how to use each method:Let’s first assume a scenario. You get the company’s salary list for this month. Assume that your salary is 9000; the array composed of company employee salaries is salaries=[8500 ,12000,9900,9000],
a. I want to know if your salary is the lowest;
b. I want to know if anyone has the same salary as you;
c. I want to know if everyone is treated the same;
###d. I want to change everyone’s salary into data in K###var a,b,c; var your=9000; var salaries=[8500,12000,9900,9000]; a=slaries.some(function(item,index,array){ return item<9000 }); console.log(a);//true;恭喜你,还有人比你工资更低 b=salaries.filter(function(item,index,array){ return item== your; }) console.log(b);//[9000] 呵呵,有人跟你待遇一样 c=salaries.every(function(item,index,array){ return item==your; }); console.log(c);//false .不是所有人都和你一样待遇哦 d=salaries.map(function(item,index,array){ return item/1000 }); console.log(d);//[8.5,12,9.9,9]
The above is the detailed content of Sharing methods for JavaScript array iteration implementation. For more information, please follow other related articles on the PHP Chinese website!