Home >Web Front-end >JS Tutorial >Detailed explanation of javaScript array iteration method_javascript skills
This article introduces the javaScript array iteration method for your reference. The specific content is as follows
Each method accepts two arguments: the function to run on each item and (optionally) the scope object to run the function on.
The functions passed into these methods receive three parameters: the value of the array item, the position of the item in the array, and the array object itself.
forEach() Run the given function on each item in the array. This method has no return value.
every() Runs the given function on every item in the array and returns true if every item in the array returns true.
some() Runs the given function on each item in the array and returns true if any item in the array returns true.
filter() Returns true if each item in the array returns true. Returns an array of items that this function will return true.
map() Returns true if each item in the array returns true. Returns an array of the results of each function call.
Please see the following example:
var numbers = [1,2,3,4,5,4,3,2,1]; //every() 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] //forEach() numbers.forEach(function(item, index, array){ alert(item); }); //多个弹窗分别显示数组中的元素
Another javaScript array iteration method, as follows
var arr = [3,4,5,6,7,"a"]; var isNum = function(elem,index,AAA){ return !isNaN(elem); } var toUpperCase = function(elem){ return String.prototype.toUpperCase.apply(elem); } var print = function(elem,index){ console.log(index+"."+elem); } /*对数组中的每一项执行测试函数,直到获得对指定的函数返回 false 的项。 使用此方法 可确定数组中的所有项是否满足某一条件,类似于&&的含义*/ var res = arr.every(isNum); console.log(res);//false; /*对数组中的每一项执行测试函数,直到获得返回 true 的项。 使用此方法确定数组中的所有项是否满足条件.类似于||的含义*/ res = arr.some(isNum); console.log(res);//true /*对数组中的每一项执行测试函数,并构造一个新数组,返回 true的项被添加进新数组。 如果某项返回 false,则新数组中将不包含此项*/ res = arr.filter(isNum); console.log(res);//[3, 4, 5, 6, 7] /*对数组中的每一项执行函数并构造一个新数组,并将原始数组中的每一项的函数结添加进新数组。*/ res = arr.map(toUpperCase); console.log(res);//["3", "4", "5", "6", "7", "A"] /*对数组中的每一项执行函数,不返回值*/ res = arr.forEach(print); console.log(res); //自己扩展 /*Array.prototype.every = function(fun,obj) { var len = this.length; if (typeof fun != "function") throw new TypeError(); for (var i = 0; i < len; i++) { if (!fun.call(obj,this[i], i,this)) return false; } return true; };*/
The above is the entire content of this article. I hope it will be helpful for everyone to learn the javaScript array iteration method.