代码如下:
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 个对象,但肯定具有三个属性:0
、1
、humans
,因此 3 次。
invertedPeninsula.inhabitants.forEach(function(habitat){
console.log(habitat.name);
});
Array.forEach
是您最好的选择,因为它遍历编号的属性。普通的 for
循环也可以。
关于javascript - 有人可以向我解释一下 for-in 循环在这里是如何被调用 3 次的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274287/