数组迭代的方法
分类:
IT文章
•
2023-12-27 11:11:55
一般有foreach,every,filter,map,some,还有es6新加的 reduce / reduceRight 和 find / findIndex 对低版本的浏览器的兼容不太好
1.
var arr = [1, 2, 3];
arr.forEach(function (element, index, array) {
console.log(element, index, array)
})
//output
1 0 [1, 2, 3]
2 1 [1, 2, 3]
3 2 [1, 2, 3]
View Code
forEach方法是这些方法里面最基本的一个方法,它的作用是对数组的每个元素执行一次提供的函数。forEach方法还可以传入第二个参数,这个参数是可选的。如果给forEach传递了第二个参数,callback函数里的this
将指向这个参数。如果没有传入第二个参数,则this
指向全局对象(在浏览器是为window),严格模式下是undefined
。
forEach方法中的callback函数会被依次传入三个参数:
2.
every方法与some方法相对,every方法是数组中的所有值都符合你给定的判断条件的时候才会返回true
,否则就返回false
。
function isBigEnough(element, index, array) {
return element >= 3;
}
var passed = [2, 3, 4].every(isBigEnough);
var passed2 = [3, 4, 5].every(isBigEnough);
console.log(passed); // false
console.log(passed2); // true
View Code
3.
filter为“过滤”、“筛选”的意思。指数组filter后,返回过滤后的新数组。用法和参数跟map差不多。
与map方法不同的是,filter方法的callback函数需要返回弱等于true
或false
的值。如果为true
,则通过,否则,不通过。
var arr = [0, 1, 2, 3];
var newArr = arr.filter(function (element, index, array) {
return e;
})
var newArr2 = arr.filter(function (element, index, array) {
return e>=2;
})
console.log(newArr); // [1, 2, 3]
console.log(newArr2); // [2, 3]
View Code
4.
map方法的作用就是将原数组按照一定的规则映射成一个新的数组。再将其返回,是返回一个新的数组,而不是将原数组直接改变。使用方法和参数都跟forEach相似。
callback需要有return值,如果没有,就像下面这样:
var data = [1, 2, 3];
var arrayOfSquares = data.map(function (element) {
element * element;
});
console.log(arrayOfSquares); // [undefined, undefined, undefined]
View Code
5.
some方法是只要数组中的某个值,符合你给定的判断条件就返回true
;否则,返回false
。用法和参数跟前面的方法一样。
function isBigEnough(element, index, array) {
return element >= 4;
}
var passed = [1, 2, 3].some(isBigEnough);
var passed2 = [1, 2, 3, 4].some(isBigEnough);
console.log(passed); // false
console.log(passed2); // true
View Code
6.
reduce / reduceRight 方法比上面的几种方法要复杂一些;它的语法如下:
array.reduce(callback,[initialValue(初始值)])
其中callback
可以依次接受四个参数:
不提供initialValue
,reduce方法会从索引1的地方开始执行callback
方法,跳过第一个索引。提供 initialValue
,从索引0开始。
是否提供initialValue
对于回调函数第一次执行时,accumulator
和currentValue
的取值有两种情况:调用reduce时提供initialValue
,accumulator
取值为initialValue
,currentValue
取数组中的第一个值;没有提供initialValue
,accumulator
取数组中的第一个值,currentValue
取数组中的第二个值。
reduceRight与reduce类似,不同之处在于它是从最后一个值开始计算的。
7.
find / findIndex
find方法用于找出第一个符合条件的数组成员。它的参数跟forEach方法是一样的;所有数组成员依次执行回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。
var value = [1, 5, 10, 15].find(function(element, index, array) {
return element > 9;
});
var value2 = [1, 5, 10, 15].find(function(element, index, array) {
return element > 20;
});
console.log(value); // 10
console.log(value2); // undefined
View Code
findIndex方法和find相似;不过它返回数组中符合条件的元素的索引。如果所有成员都不符合条件,则返回-1。
var value = [1, 5, 10, 15].findIndex(function(element, index, array) {
return element > 9;
});
var value2 = [1, 5, 10, 15].findIndex(function(element, index, array) {
return element > 20;
});
console.log(value); // 2
console.log(value2); // -1
View Code
转自 https://segmentfault.com/a/1190000009943551