This article mainly introduces the relevant information about the javascript iteration method. if you need it, you can refer to the following five iteration methods to accept two parameters: the function to be run on each item and the scope of the function to be run (optional)
Every (): Run the given function for each item in the array. If the function returns true for each item, true is returned.
Filter (): Run the given function for each item in the array. Returns an array composed of true items.
ForEach (): Run the given function for each item in the array. This function does not return values.
Map (): Run the given function for each item in the array. Returns a function composed of the results of each function call.
Some (): Run the given function for each item in the array. Returns true if the function returns true for any item.
The code is as follows:
Var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
// Every () and some () are the most similar
// Every () item: current traversal item, index: current item index, array: array object itself
Var everyResult = numbers. every (function (item, index, array ){
Return item> 2;
});
Alert (everyResult); // false
// Some ()
Var someResult = numbers. some (function (item, index, array ){
Return item> 2;
});
Alert (someResult); // true
// Filter
Var filterResult = numbers. filter (function (item, index, array ){
Return item> 2;
});
Alert (filterResult); // [3, 4, 5, 4, 3]
// Map ()
Var mapResult = numbers. map (function (item, index, array ){
Return (item * 2 );
});
Alert (mapResult); // [2, 4, 6, 8, 10, 8, 6, 4, 2]
// There is no difference between forEach and for loop.
Var forEachResult = numbers. forEach (function (item, index, array ){
Alert (item)
});
The above is all the content of this article. I hope to give you some tips to better understand the javascript iteration method.