Iteration methods of arrays in JS forEach, map, filter, reduce, every, some
In the daily process of processing JS arrays, we usually use for loops. Implementation. The following summarizes some commonly used array iteration methods other than for loops.
forEach (loop)
Let each item of the array do one thing Things
let a = [1,2,3]; a.forEach(function(value,i){ console.log("第" + (i + 1) + "项 :" + value) }) // 第1项 :1 // 第2项 :2 // 第3项 :3
map (mapping)
is similar to forEach, but map has a return value and generates a new array without changing the original array
let a = [1,2,3]; a.map(function(value,i){ return value * 2 }) // 第1项 :2 // 第2项 :4 // 第3项 :6
Comparison between map and forEach:
// 没有返回值的forEach: let a = [1, 2, 3]; a = a.forEach(function (value, i) { return value * 2 // undefine }) // 有返回值的map: let b = [1, 2, 3]; b = b.map(function (value, i) { return value * 2 // [2,4,6] })
Possible pitfalls: There are more comma separators between the data processed by map
Reason: After map traversal, it is still an array, and the array elements separated by commas. When inserting into the DOM, only toString is called. The comma separators between the array elements are also brought in. After traversing the map, directly concatenating them into strings will eliminate this problem.
How to deal with it : map is followed by .join('')
reduce (cumulative)
reduce() method receives a function as an accumulator, each value in the array (from left to right) starts to reduce and finally calculates to a single value.
reduce() can be used as a higher-order function for compose of functions.
Note: reduce() will not execute the callback function for an empty array.
Calculate the previous and subsequent items
let a = [1, 2, 3]; a = a.reduce(function (prev, next) { return prev + next // 1+2+3 = 6 })
filter (filter)
Filter out values that do not meet the conditions and return a new array
let a = [1, 2, 3]; a = a.filter(function (value, i) { return value > 2 }) console.log(a) // 3
every (all)
Determine whether each element meets the conditions, if so, return true, otherwise false
let a = [1, 2, 3]; a = a.every(function (value, i) { return value > 2 }) console.log(a) // false
some (arbitrary)
Judge whether any of each element meets the condition, if so, return true, otherwise false
let a = [1, 2, 3]; a = a.every(function (value, i) { return value > 2 }) console.log(a) // true
Recommended tutorial: "JS Tutorial》
The above is the detailed content of Iteration methods of arrays in JS: filter, reduce, every, some. For more information, please follow other related articles on the PHP Chinese website!