JavaScript五中迭代方法小解

ECMAScript 为数组定义了五个迭代方法。
每个方法都接收两个参数:要在每一项上运行的函数和(可选的)运行该函数的作用域对象——影响this的值。
传入这些方法中的函数会接收三个参数:数组项的值、该项在数组中的位置和数组对象本省。
根据使用的方法不同,这个函数执行后的返回值可能会也可能不会影响方法的返回值。
以下是这五个迭代方法的作用。

1、every(); 对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true。

2、some(); 对数组的每一项运行给定函数,如果该函数对任一项返回true,则返回true。

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyResult = numbers.every(function(item, index, array){
return (item > 3);
})
console.log(everyResult); //false

var someResult = numbers.some(function(item, index, array) {
return (item > 3);
})
console.log(someResult); //true

3、filter(); 对数组中的每一项运行给定函数,返回改函数会返回true的项组成的数组。

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var filterResult = numbers.filter(function(item, index, array) {
return (item > 3);
})
console.log(filterResult); //[4, 5, 4]

4、map(); 对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var mapResult = numbers.map(function(item, index, array) {
return item * 2;
})
console.log(mapResult); //[2, 4, 6, 8, 10, 8, 6, 4, 2]

5、forEach(); 对数组中的每一项运行给定的函数,该方法没有返回值,本质上于使用for循环迭代数组一样。

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.forEach(function(item, index, array) {
//执行某些操作
})

原文路径:https://segmentfault.com/a/1190000009940387

内容仅个人学习使用,不能作为商业用途,一经发现责任自负!

posted @ 2019-09-16 20:54  jageLee  阅读(203)  评论(0编辑  收藏  举报