Array.prototype.myMap = function(func) {
var newArray = new Array;
// for in存在会额外输出“重写的myMap自身代码”的问题
for (i in this) {
// if (i != "myMap") //该行用于完善功能
newArray.push(func(this[i], i, this));
}
// 下面的forEach完美实现。
// this.forEach(function(v, i, a) {
// newArray.push(func(v, i, a));
// })
return newArray;
}
var arr1 = [1, 2, 3, 4, 5];
var arr2 = arr1.myMap((value, index, arr) => {
console.log(value, index, arr);
return value * index;
})
console.log(arr2);
当前代码输出:
控制台打印:
作为参考的forEach实现完美,不会打印多余的内容。
所以该提问焦点是:for/in这里打印非预期的原因和底层?为什么会额外循环一次输出“myMap自身代码”?
ps:小白勿喷,觉得菜可以踩,555.
给你摘抄一下MDN关于for...in循环的说明
"The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable propertie"
关键部分给你标出来了,你品,你细品