#Javascript数组的5种迭代方法
The 5 iterations are defined in the array, and the functions in these methods accept three parameters, the value of the array item, the position of the item in the array, and the group object itself, and the following are the functions of the 5 iteration methods.
1, every method:
Runs the given function for each item in the array, and returns True if the function returns true for each item.
let arr1 = [1,2,3,4,5,6];let arr2 = [-1,-2,-3,-4,-5,-6];let every1 = arr1.every((item,index,arr)=>{ return item>0})let every2 = arr2.every((item,index,arr)=>{ return item>0})console.log(every1,every2);//true,false
2. Filter method
Runs the given function for each item in the array, returns the number of items that the function returns True
let arr1 = [-1,-2,-3,4,5,6];let arr2 = [1,2,3,-4,-5,-6];let filter1 = arr1.filter(item=>{ return item>0})let filter2 = arr2.filter((item)=>{ return item<0})console.log(filter1,filter2);//[4,5,6],[-4,-5,-6]
3. Some method
Runs the given function for each item in the array, and returns True if the function returns true for either item.
let arr1 = [1,2,3,4,5,6];let arr2 = [1,2,3,-4,-5,-6];let some1= arr1.some(item=>{ return item>0})let some2 = arr2.some((item)=>{ return item>0})console.log(some1,some2);//true,true
4. The Foreach method
Runs the given function for each item in the array, and the method does not return a value.
foreach cannot traverse object
foreach cannot be used in IE, but it is implemented in Firefox and Chrome.
let arr1 = [1,2,3,4,5,6];let arr2 = [1,2,3,-4,-5,-6];let forEach1= arr1.forEach(item=>{ return item++})let forEach2 = arr2.forEach((item)=>{ return item++})console.log(forEach1,forEach2);//undefined,undefined
5. Map method
Each item in the array runs the given function, returning an array of the results of each call.
let arr1 = [1,2,3,4,5,6];let arr2 = [-1,-2,-3,-4,-5,-6];let map1 = arr1.map(item=>{ return ++item})let map2 = arr2.map((item)=>{ return ++item})console.log(map1,map2);//[2, 3, 4, 5, 6, 7] (6) [0, -1, -2, -3, -4, -5];
In the development process used in the more commonly used is the Map,foreach method, they are more similar but there is no small difference.
The main reason is:
1, the Map method has a return value, and foreach is not.
2, IE browser does not support the Foreach method, so to be compatible with IE browser try not to use foreach to traverse.
3. The map method is faster than foreach.
5 iterative methods for JavaScript arrays