js重写原型函数时关于for/in的问题

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);

当前代码输出:
image.png
控制台打印:
image.png
作为参考的forEach实现完美,不会打印多余的内容。
所以该提问焦点是:for/in这里打印非预期的原因和底层?为什么会额外循环一次输出“myMap自身代码”?
ps:小白勿喷,觉得菜可以踩,555.

阅读 1.5k
1 个回答

给你摘抄一下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"

关键部分给你标出来了,你品,你细品

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题