手动实现map、filter、redue

实际上,map/filter/reduce 也是基于 for 循环封装来的,通过高阶映射实现。

map

// 使用 for 循环
const arr1 = [1, 2, 3];
let arr2 = [];
for (let i = 0; i < arr1.length; i++) {
    arr2.push(arr1[i] * 2);
}
console.log(arr2); // [2, 4, 6]

// 使用 map 方法
const arr1 = [1, 2, 3];
const arr2 = arr1.map(item => item * 2);
console.log(arr2); // [2, 4, 6]

// 实现自己的 map 方法
Array.prototype.myMap = function(fn) {
    const newArr = [];
    for (let i = 0; i < this.length; i++) {
        newArr.push(fn(this[i]));
    }
    return newArr;
};
const arr1 = [1, 2, 3];
const arr2 = arr1.myMap(item => item * 2);
console.log(arr2); // [2, 4, 6]

filter

// 使用 for 循环
const arr1 = [1, 2, 3];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
    arr1[i] > 2 && arr2.push(arr1[i]);
}
console.log(arr2); // [3]

// 使用 filter 方法
const arr1 = [1, 2, 3];
const arr2 = arr1.filter(item => item > 2);
console.log(arr2); // [3]

// 实现自己的 filter 方法
Array.prototype.myFilter = function(fn) {
    const newArr = [];
    for (let i = 0; i < this.length; i++) {
        fn(this[i]) && newArr.push(this[i]);
    }
    return newArr;
};
const arr1 = [1, 2, 3];
const arr2 = arr1.myFilter(item => item > 2);
console.log(arr2); // [3]

reduce

// 使用 for 循环
const arr1 = [1, 2, 3];
let sum = 0;
for (let i = 0; i < arr1.length; i++) {
    sum = sum + arr1[i];
}
console.log(sum);

// 使用 reudce 方法
const arr1 = [1, 2, 3];
const sum = arr1.reduce((perv, current) => {
    return perv + current;
});
console.log(sum);

// 实现自己的 reduce 方法
Array.prototype.myReduce = function(fn, initValue) {
    for (let i = 0; i < this.length; i++) {
      initValue = fn(initValue, this[i], i, this);
    }
    return initValue;
};
const arr1 = [1, 2, 3];
const sum = arr1.myReduce((perv, current) => {
  return perv + current;
}, 0);
console.log(sum);

你可能感兴趣的:(手动实现map、filter、redue)