The four commonly used new methods for arrays in es6 are: 1. forEach(), which is used to traverse the array with no return value; 2. filter(), which filters out values in the array that do not meet the conditions; 3 , map(), traverses the array and returns a new array; 4. reduce(), performs some calculation on the first and last two items of the array, and then returns its value.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
There are four new very practical array methods in ES6, including: forEach, filter, map, and reduce.
1.forEach
Traverse the array, no return value, do not change the original array, just traverse - equivalent to for loop traversal
1 2 3 4 5 6 7 8 9 10 11 |
|
2.filter:
filter() function filters out values in the array that do not meet the conditions , if the callback function returns true, leave it and return a new array without changing the original array! ! ! Can be used to deduplicate arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
3.map:
map traverses the array and returns A new array, without changing the original array, mapped one to one, mapped to a new array
1 2 3 4 5 6 7 8 9 10 11 |
|
4.reduce:
reduce() summarizes a bunch of them into one (for example, calculating the total, calculating the average), reduce makes the two items before and after the array perform some calculation, and then returns its value and continues the calculation. The original array is not changed and the final result of the calculation is returned. If no initial value is given, traversal starts from the second item of the array
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
, the first parameter callback function, the second parameter initial value
4.1Sum
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|
4.2 Find the average
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
[Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of What are the 4 commonly used methods for adding new arrays in es6?. For more information, please follow other related articles on the PHP Chinese website!