大约 1 分钟
Javascrpt 中 方法forEach map filter
1、forEach
对数组按照升序堆数组进行遍历
array.forEach(callback(currentVal, index, array) {
// do something
}, thisArg)
##范 列
["1","2","3"].forEach((c,i,a)=>{
console.log(c);#1,2,3
console.log(i);#0,1,2
},arry2)
2、map
首先来一个经典面试题
["1", "2", "3"].map(parseInt)
答案:[1, NaN, NaN]
解析: 我们可以看下console.log(parseInt.length)#2
parseInt默认会有2个参数,第一个是值,第二个是索引
所以 parseInt("1",0) #0代表10进制所以为1
parseInt("2",1) #不存在1进制,所以为NaN
parseInt("3",2) #2进制中不存在“3”,所以为NaN
3、filter
filter过滤的方法,下图为案例
var filtered = [12, 5, 8, 130, 44].filter(function(v) {
return v >= 10
})
// [12, 130, 44]
var filtered = [12,5,8,130,44].filter((v) => {
return v >= 10
})
//[12,130,44]
4、reduce
**reduce()**
方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
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 他们四者的区别
相同点:
- 都会循环遍历数组中的每一项;
- map()、forEach()和filter()方法里每次执行匿名函数都支持3个参数,参数分别是:当前元素、当前元素的索引、当前元素所属的数组;
- 匿名函数中的this都是指向window;
- 只能遍历数组。
不同点:
- map()速度比forEach()快;
- **map()和filter()会返回一个新数组,不对原数组产生影响;forEach()不会产生新数组,返回undefined;**reduce()函数是把数组缩减为一个值(比如求和、求积);
- reduce()有4个参数,第一个参数为初始值。