面试官:写一下数组方法叭。

104 阅读1分钟

注意点:map和filter可以使用reduce来写,这一点也常考哦!

map

Array.prototype.myMap = function (fn) {
    if (typeof arguments[0] !== 'function') throw new Error(arguments[0] + ' is not a function');
    let arr = this;
    let len = arr.length;
    let temp = new Array(len)
    for (let i = 0; i < len; i++) {
        let res = arguments[0](arr[i], i, arr)
        temp[i] = res;
    }
    return temp;
}
//reduce来写
Array.prototype.myMap = function (...args) {
    if (typeof args[0] !== 'function') throw new Error(`${args[0]} is not a function`);
    let arr = this;
    return arr.reduce((prev, cur, i, arr) => {
        prev.push(args[0](cur, i, arr));
        return prev;
    }, []);
}

filter

Array.prototype.myFilter = function (fn) {
    if (typeof fn !== 'function') {
        throw new TypeError(`${fn} is not a function`)
    }
    const arr = this;
    const len = this.length;
    const temp = [];
    for (let i = 0; i < len; i++) {
        const result = fn.call(arguments[1], arr[i], i, arr);
        result && temp.push(arr[i])
    }
    return temp;
}
//reduce来写
Array.prototype.myFilter = function (fn) {
    if (typeof fn !== 'function') throw new Error(`${fn} is not a function`);

    let res = [];
    for (let i = 0; i < this.length; i++) {
        let result = fn(this[i], i, this);
        result && res.push(this[i])
    }
    return res
}

reduce

Array.prototype.myReduce = function (fn, temp) {
    if (typeof fn !== 'function') throw new Error(`${fn} is not a function`);

    let arr = this;
    let index = 0;
    let res = temp || arr[index++];

    while (index < arr.length) {
        res = fn(res, arr[index], index, arr);
        index++;
    }
    return res;
}

forEach

Array.prototype.myForEach = function (...args) {
    if (typeof args[0] !== 'function') throw new Error(`${args[0]} is not a function`)

    let arr = this;

    arr.reduce((prev, cur, index, arr) => {
        args[0](cur, index, arr)
    }, 0)
}

记录记录!