繁体   English   中英

Array.prototype.map的两种实现方式有什么区别

[英]What are the differences between the two ways to implement Array.prototype.map

Array.prototype.myMap = function (cb, thisArg) {
    const newArr = []
    for (let i = 0; i < this.length; i++) {
        if (i in this) {
            newArr[i] = cb.call(thisArg, this[i], i, this)
        }
    }
    return newArr
}
Array.prototype.myMap = function (cb, thisArg) {
    const newArr = []
    const len = this.length
    for (let i = 0; i < len; i++) {
        if (i in this) {
            newArr[i] = cb.call(thisArg, this[i], i, this)
        }
    }
    return newArr
}

我不知道为什么“i < this.length”没有通过任何测试用例,它总是显示无限

如果回调 function 修改了被迭代的数组的长度,这些将有所不同。 例如:

[1, 2, 3].myMap((el, index, array) => {
    array.push(0);
    return el + 1;
});

第二个版本永远不会结束,因为this.length随着循环的继续而不断增加。 但第一个版本只处理数组的原始 3 个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM