【问题标题】:strange behaviour from loops in javascriptjavascript中循环的奇怪行为
【发布时间】:2018-08-06 18:18:13
【问题描述】:

我有一个这样的对象:

{1:{x:21, y:54}, 2:{x:80,y:20}, ...}

我想将另一个 x,y 与我的对象 x,y 进行比较。如果它们相同,我会从我的对象中删除那个 x,y。现在当我这样做时:

  for(let i in myObj){
    if(myObj[i].x === info.x && myObj[i].y === info.y){
      delete myObj[i]
    }
  }

效果很好。

但是当我这样做时:

  for(let i=0; i<=5; i++){
    if(myObj[i].x === info.x && myObj[i].y === info.y){
      delete myObj[i]
    }
  }

我从 myObj[i].x 收到错误:

无法读取未定义的属性“x”

我的问题是为什么我的第一种方法不起作用?我花了半天时间认为问题出在其他地方。我将不胜感激。

【问题讨论】:

  • 使用调试器。 myObj[0] 存在吗?
  • 您的myObj 对象是否有密钥0?请尝试使用浏览器的debugging capabilities
  • 当你使用 for..in 循环时,你迭代的是每一项,而不是索引。
  • for (let i = 1; ... 可能会起作用,因为根据您的示例对象,没有带有键0 的对象,第一个键是1。 (我们说的是keys,而不是index
  • @Pavitra 如果“item”是指“value”,那就错了。 for-in 遍历键。 for-of 迭代 values。常规的 for 循环遍历数字键。

标签: javascript loops object for-loop


【解决方案1】:

for 和 for...in 循环的基本区别在于它们的迭代方式。 for 循环遍历索引值,而 for...in 遍历存在的项目。示例:

var myObj = {
  firstObj : "first value",
  secondObj : "second value"
};

console.log(myObj[0]);     // undefined
console.log(myObj['firstObj']); //"first value"
console.log(myObj.firstObj);   //"first value"

var seconObj = [
  {
    a : "a value",
    a2 : "a2 value"
  },
  {
    b : "b value",
    b2 : "b2 value"
  }
];

console.log(seconObj[0].a); // "a value"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    相关资源
    最近更新 更多