native Array Reduce Implementation问题

时间:2018-02-27 22:09:07

标签: javascript arrays

我试图实现Native reduce:

Array.prototype.myReduce = function(callback, initialVal) {
    var accumulator = (initialVal === undefined) ? undefined : initialVal;
    for (var i = 0; i < this.length; i++) {
        if (accumulator !== undefined)
            accumulator = callback.call(undefined, accumulator, this[i], i, this);
        else
            accumulator = this[i];
    }
    return accumulator;
};

大多数测试运行正常,但是当我尝试运行它时,它失败了:

Original Reduce:

[1,2,3,4,5].reduce((carry, val, i, arr) => { console.log('arr', arr); arr[arr.length] = val; return carry;  }, []);

// Iterated 5 times
arr (5) [1, 2, 3, 4, 5]
arr (6) [1, 2, 3, 4, 5, 1]
arr (7) [1, 2, 3, 4, 5, 1, 2]
arr (8) [1, 2, 3, 4, 5, 1, 2, 3]
arr (9) [1, 2, 3, 4, 5, 1, 2, 3, 4]

Myreduce:

[1,2,3,4,5].myReduce((carry, val, i, arr) => { console.log('arr', arr); arr[arr.length] = val; return carry;  }, []);

// Infinite recursion, since we are pushing every time
arr (5) [1, 2, 3, 4, 5]
arr (6) [1, 2, 3, 4, 5, 1]
arr (7) [1, 2, 3, 4, 5, 1, 2]
arr (8) [1, 2, 3, 4, 5, 1, 2, 3]
arr (9) [1, 2, 3, 4, 5, 1, 2, 3, 4]
arr (10) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
arr (11) [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1]

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:3)

你改变原始数组,因此永远不会到达this.length

您应该将原始数组的长度存储在某处并使用它。

例如:

Array.prototype.myReduce = function(callback, initialVal) {
    var accumulator = (initialVal === undefined) ? undefined : initialVal;
    var len = this.length;

    for (var i = 0; i < len; i++) {
        if (accumulator !== undefined)
            accumulator = callback.call(undefined, accumulator, this[i], i, this);
        else
            accumulator = this[i];
    }
    return accumulator;
};