我
使用 reduce 方法实现 forEach、map、filter
难度:
js
// forEach
function forEachUseReduce(array, handler) {
array.reduce(function (pre, item, index) {
handler(item, index);
}, null);
}
// map
function mapUseReduce(array, handler) {
let result = [];
array.reduce(function (pre, item, index) {
let mapItem = handler(item, index);
result.push(mapItem);
}, null);
return result;
}
// filter
function filterUseReduce(array, handler) {
let result = [];
array.reduce(function (pre, item, index) {
if (handler(item, index)) {
result.push(item);
}
}, null);
return result;
}