javascript 在[duplicate]中使用for循环时arr结尾为空

cwtwac6a  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(96)
    • 此问题在此处已有答案**:

Why is using "for...in" for array iteration a bad idea?(28个答案)
How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop(4个答案)
2小时前关闭.

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循环,但我只想知道为什么会出现这个问题**
lx0bsm1f

lx0bsm1f1#

for...in循环也正在查找myMap属性。请执行Object.hasOwn检查,使用{enumerable: false}定义该属性,或者不使用for...in进行循环。
使用Array#entries循环元素沿着索引:

Array.prototype.myMap = function(callback) {
  const newArray = [];
  for(const [i, elem] of this.entries()){
    newArray.push(callback(elem, i, this))
  }
  return newArray;
};

console.log([1, 2, 3, 4, 5].myMap(item => item * 2))

正在检查自己的属性:

Array.prototype.myMap = function(callback) {
  const newArray = [];
  for(let i in this)
    if (Object.hasOwn(this, i))
      newArray.push(callback(this[i], i, this));
  return newArray;
};

console.log([1, 2, 3, 4, 5].myMap(item => item * 2))

使用{enumerable: false}定义myMap

Object.defineProperty(Array.prototype, 'myMap', {
  value(callback) {
    const newArray = [];
    for (let i in this) {
      newArray.push(callback(this[i], i, this))
    }
    return newArray;
  },
  enumerable: false // this is the default, so it can be omitted
});
console.log([1, 2, 3, 4, 5].myMap(item => item * 2))

相关问题