forEach、map、filter、reduce的区别

1.相同点:

  • 都会循环遍历数组中的每一项;
  • map()、forEach()和filter()方法里每次执行匿名函数都支持3个参数,参数分别是:当前元素、当前元素的索引、当前元素所属的数组;
  • 匿名函数中的this都是指向window;
  • 只能遍历数组。

2.不同点:

  • map()速度比forEach()快;
  • map()和filter()会返回一个新数组,不对原数组产生影响;forEach()不会产生新数组,返回undefined;reduce()函数是把数组缩减为一个值(比如求和、求积);
  • reduce()有4个参数,第一个参数为初始值。

3.forEach使用

var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  console.log(element);
});

 

4.map使用

var array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

 

5.filter使用

var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

 

6.reduce使用

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

 

转载于:https://www.cnblogs.com/kaiqinzhang/p/11496151.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值