1. The realization of a map

function map(arr, cb) {
    if (!Array.isArray(arr) || ! arr.length ||typeofcb ! = ='function') {
        return [];
    }
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        result.push(cb(arr[i], i, arr));
    }
    return result;
}

Array.prototype.map=function(cb){
    return map(this,cb);
}
const result=[1.2.3.4].map((item,index) = >item>3);
console.log(result)

Copy the code

2. The realization of the filter

function filter(arr, cb) {
    if (!Array.isArray(arr) || ! arr.length ||typeofcb ! = ='function') {
        return [];
    }
    const result = [];
    for (let i = 0; i < arr.length; i++) {
        cb(arr[i], i, arr)&&result.push(arr[i]);
    }
    return result;
}

Array.prototype.filter = function (cb) {
    return filter(this, cb);
}

const result = [1.2.3.4.5].filter(item= > item > 4);
console.log(result)
Copy the code

3. Reduce the implementation

function reduce(arr, initialValue, cb) {
    if (!Array.isArray(arr) || ! arr.length ||typeofcb ! = ='function') {
        return [];
    }
    consthasInitialValue = initialValue ! = =undefined;
    let value = hasInitialValue ? initialValue : arr[0];
    for (let i = hasInitialValue ? 0 : 1; i < arr.length; i++) {
        value = cb(value, arr[i], i, arr);
    }
    return value;
}

Array.prototype.reduce = function (cb, initialValue) {
    return reduce(this, initialValue, cb)
}

const result = [1.2.3.4.5].reduce((memo, current, index) = > {
    memo.push(current + 1)
    returnmemo; } []);console.log(result)
Copy the code