preface
Cut the crap and get to the point.
1 forEach (make each item in the array do one thing)
If you don’t do something special, in general, it won’t break. If you need to break out of the loop, use the for statement instead.
let arr = [1.2.3.4.5];
arr.forEach((item,index) = > {
console.log(item);
})
/ / 1, 2, 3, 4, 5
Copy the code
2 map (make an array produce a new array by some calculation)
let arr = [1.2.3.4.5];
let newArray = arr.map((item,index) = > {
return item * 2
});
newArray // [2, 4, 6, 8, 10]
arr / / [1, 2, 3, 4, 5]
Copy the code
This returns a new array, it doesn’t change the original array.
3 reduce (Do some sort of calculation on the front and back of the array and add up the final value)
let arr = [1.2.3.4.5];
let result = arr.reduce((prev, cur, index, arr) = > {
return prev + cur;
});
Copy the code
CallbackFunction contains four parameters, to explain what they mean:
Prev: the value of the first item or the result of the last stack cur: the current item that will be added index: the current index arr: the array itself
In this case, the default initialValue is [0] of the array. If you want to customize the initialValue, you can add a second parameter (initialValue) to reduce, as follows
let result = arr.reduce((prev, cur, index, arr) = > {
return prev + cur;
}, - 5);
// If the initialValue is a sum, be sure to note the type of the initialValue. If set to a string, the result is a string according to "add them together and the value type is the same as the first addend".
Copy the code
4 filter (Returns a new array if the item in the filter array matches the criteria)
let arr = [1.2.3.4.5];
let newArray = arr.filter((item,index) = > {
return item > 3;
});
newArray / / (4, 5)
Copy the code
5 every (checks whether each item in the array meets the criteria)
You can think of it as ampersand and
let arr = [1.2.3.4.5];
let result = arr.every((item,index) = > {
return item > 0;
});
result // true
Copy the code
6 some (Check if any items in the array match the criteria)
Can understand as | | ‘or’ relationship
let arr = [1.2.3.4.5];
let result = arr.some((item,index) = > {
return item > 2;
});
result // true
Copy the code