实现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
}

为什么"strong";i<这个长度"我不知道为什么没有通过任何测试用例,它总是显示无限

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

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

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

最新更新