【发布时间】:2023-01-29 01:08:57
【问题描述】:
Array.prototype.myMap = function(callback) {
const newArray = [];
// Only change code below this line
for(let i in this){
newArray.push(callback(this[i], i, this))
}
// Only change code above this line
return newArray;
};
console.log([1, 2, 3, 4, 5].myMap(item => item * 2))
type here
结果显示像
[ 2, 4, 6, 8, 10, NaN ]
我期待结果是这样的:
[ 2, 4, 6, 8, 10 ]
如果我在循环中使用 for,谁能解释为什么我的 arr 末尾有这个 null
**我知道这适用于普通的 for 循环,但我只想知道为什么我们会遇到这个问题 **
【问题讨论】:
-
不要使用
for ... in迭代数组,或者更好的是,根本不要使用for ... in。此外,不要污染本地人,尤其是具有可枚举属性的本地人,这是你在这里的垮台。for ... in也迭代了原型链,而你的原型方法是可枚举的,所以会被包含在迭代中。