首页 > 其他 > 详细

forEach、map、filter、reduce的区别

时间:2019-09-10 12:38:32      阅读:82      评论:0      收藏:0      [点我收藏+]

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

 

forEach、map、filter、reduce的区别

原文:https://www.cnblogs.com/kaiqinzhang/p/11496151.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!