javascript - 有人可以向我解释一下 for-in 循环在这里是如何被调用 3 次的吗?

标签 javascript loops for-in-loop

代码如下:

var InvertedPeninsula = function() {
  this.inhabitants = [
    {
      name: 'Sir Charles',
      race: 'Human'
    },
    {
      name: 'Ealei',
      race: 'Elf'
    }
  ];
  // Adds an extra humans method property to the inhabitants array to return all Humans
  this.inhabitants.humans = function() { /* returns all Human inhabitants */ };
};

// Create a new invertedPeninsula
var invertedPeninsula = new InvertedPeninsula();

// Log the name of each invertedPeninsula inhabitant
for (var i in invertedPeninsula.inhabitants) {
  console.log(invertedPeninsula.inhabitants[i].name);
}

对我来说,它看起来像是 2x。 3x从哪里来?数组中只有 2 个单元格。

最佳答案

这正是他们使用 for...in 迭代数组时遇到的陷阱。 for...in 遍历所有可枚举属性,因此 humans 也被迭代。

数组中当然有 2 个对象,但肯定具有三个属性:01humans,因此 3 次。

invertedPeninsula.inhabitants.forEach(function(habitat){
   console.log(habitat.name);
});

Array.forEach 是您最好的选择,因为它遍历编号的属性。普通的 for 循环也可以。

关于javascript - 有人可以向我解释一下 for-in 循环在这里是如何被调用 3 次的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274287/

相关文章:

用于跨浏览器检测隐身模式(私有(private)浏览)的 JavaScript

javascript - 路由器的 prop History.location 中的路径名不会更新

循环内的 JavaScript 闭包——简单实用的示例

Python for-in-loop 停止迭代从 for-in-loop 创建的列表对象

javascript - 在 for in 循环中获取对象的名称以用作另一个对象的键

swift - 在 for-in 循环中使用字符串宽度的问题

javascript - 如何修复动画类的一部分?

php - 两列 ("gap") 布局问题

jquery - MySQL 中遍历行并删除一些数据的代码是什么?

javascript - 是否可以使用 javascript 更改实际的 css 文件?