js map, reduce, forEach, filter的一般实现

时间:2022-02-20 18:28:51

js map, reduce, forEach, filter的一般实现

map(映射), reduce(规约), forEach(遍历), filter(过滤),它们都是高阶函数,都是以传入不同的函数来以不同的方式操作数组元。

1> map

function map(array, func) {
var res = [];
for (var i = 0, len = array.length; i < len; i++) {
res.push(func(array[i]));
}
return res;
}
var res = map([1, 2, 3], function(n){
return n + 3;
});
console.log(res);// [4, 5, 6]

2>reduce

function reduce(array, func, initialValue){
var result = initialValue;
for(var i = 0, len = array.length; i < len; i++){
result = func.apply(null, [result].concat(array[i]));
}
return result;
}
var res = reduce([1, 2, 3], function(previousValue, currentValue){
return previousValue + currentValue;
}, 0);
console.log(res);// 6


3>forEach

function forEach(array, func){
for (var i = 0, len = array.length; i < len; i++) {
func(array[i]);
}
}
forEach([1, 2, 3], function(n){
console.log(n);// 1 \n 2 \n 3
});

4>filter

function filter(array, func){
var res = [];
for(var i = 0, len = array.length; i < len; i++){
if(typeof func(array[i]) !== 'undefined'){
res.push(array[i]);
}
}
return res;
}
var res = filter([1, 2, 3], function(n){
if(n % 2 == 1){
return n;
}
});
console.log(res);// [1, 3]