有人可以向我解释在这里如何调用for-in循环3次?

Mab*_*eek 2 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);
}
Run Code Online (Sandbox Code Playgroud)

对我来说,它看起来像是2x.3x来自哪里?阵列中只有2个单元格.

Ami*_*oki 7

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

当然也有阵列中的2个对象,但可以肯定有三个属性:0,1,humans因此3次.

invertedPeninsula.inhabitants.forEach(function(habitat){
   console.log(habitat.name);
});
Run Code Online (Sandbox Code Playgroud)

Array.forEach是你最好的选择,因为它迭代编号的属性.一个正常的for循环也可以.