美文网首页
JavaScript数组迭代对比 forEach、map、fil

JavaScript数组迭代对比 forEach、map、fil

作者: SailingBytes | 来源:发表于2018-12-26 09:35 被阅读0次

1、forEach

遍历数组中的每一个项(return不起作用)

arr.forEach(function(item, index) {

    item += 1;

}

2、map

遍历数组产生一个新数组

var newArr = arr.map(function(item, index) {

    return item += 1;

}

3、filter

筛选出数组中符合条件的项,生成新数组

var newArr = arr.filter(function(item, index) {

    return item >= 0;

}

4、reduce

函数累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

var result = arr.reduce(function(total, currentValue, currentIndex) {

    return prev + next;

}

total初始值,currentValue当前值,currentIndex当前索引

5、every

检查数组中的每一项是否符合条件(返回true和false)

var result = arr.every(function(item, index) {

    return item > 0;

}

6、some

检查数组中是否有某些符合条件(返回true和false)

var result = arr.some(function(item, index) {

    return item > 0;

}

相关文章

网友评论

      本文标题:JavaScript数组迭代对比 forEach、map、fil

      本文链接:https://www.haomeiwen.com/subject/twmclqtx.html