[英]Can someone explain to me how the for-in loop is called 3 times here?
這是代碼:
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
迭代數組時遇到的陷阱。 A for...in
迭代遍歷所有可枚舉屬性 ,因此humans
也在迭代。
當然也有陣列中的2個對象,但可以肯定有三個屬性 : 0
, 1
, humans
,因此3次。
invertedPeninsula.inhabitants.forEach(function(habitat){
console.log(habitat.name);
});
Array.forEach
是你最好的選擇,因為它遍歷編號的屬性。 正常for
循環也可以。
您的數組具有以下值: 0, 1, 'humans'
humans'infact您使用以下代碼添加名為'humans'的元素:
this.inhabitants.humans = function() { /* returns all Human inhabitants */ };
要檢查它,請嘗試以下代碼:
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(i); // CHANGED LINE
}
for...in
迭代所有(繼承和擁有)可枚舉屬性。
使用賦值創建屬性時,它被定義為可枚舉。 您可以使用它來使其不可枚舉(因此不會被for...in
迭代)
Object.defineProperty(this.inhabitants, 'humans', {enumerable: false});
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 */ }; Object.defineProperty(this.inhabitants, 'humans', {enumerable: false}); }; // 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); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.