【问题标题】:getting null in end of arr when looping with for in使用 for in 循环时在 arr 末尾获取 null
【发布时间】: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也迭代了原型链,而你的原型方法是可枚举的,所以会被包含在迭代中。

标签: javascript for-in-loop


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-06-14
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多