2014-03-13 47 views
-1

如何迭代JavaScript中的一組字面對象?將對象推入數組意外的結果

我願做這樣的事情:

grupo = []; // declare array 

text = {}; // declare new object 
text.a = "texta"; // declare property "a" of an object. 
text.b = "textb"; 
grupo.push(text); // add object to array 

text = {}; // declare new object 
text.a = "textc"; // declare property 
grupo.push(text); // add object with other property 

// Iterate over 
for (i=0; i<=grupo.length; i++) { 
    console.dir(grupo[i].text.a); 
} 
+0

負,但沒有解釋爲什麼,我討厭這樣。 –

+0

for(var i = 0; i Baseleus

+1

不是同一個問題...也許我沒有正確解釋,即時迭代時需要訪問對象上的屬性。 –

回答

1

有在該代碼的各種錯誤:

  1. 你把相同對象數組中的兩次,不把兩個對象在數組中。將text推入陣列後,您只需覆蓋同一對象上的a屬性並再次將其推入。你還沒有創建一個新的對象。

  2. 您還沒有聲明任何變量(您在評論中說過的任何地方「聲明」,那些都不是聲明),所以你會墮入The Horror of Implicit Globals。使用var來聲明變量。

  3. 行註釋應與//,不\\(那些引起語法錯誤)

  4. for環在端應該使用<,不<=,其終止條件開始。有關使用JavaScript循環數組的各種方法,請參閱see this question and its answers

下面是代碼的清理後的版本:

var text, grupo, i; // Declare variables 

text = {};   // Create an object and assign it to the variable 
grupo = [];   // Create an array and assign it to the variable 

text.a = "texta"; // Set the property `a` on the object 
text.b = "textb"; // Set the property `b` on the object 
grupo.push(text); // Put that object onto the array 
text = {};   // Create a second object 
text.a = "textc"; // Set the property `a` on that new object 
grupo.push(text); // Put that object on the array 

for (i=0;i<grupo.length;i++) { 
//   ^-------------------- Note no = 
    console.dir(grupo[i].text.a); 
} 
+1

thx,我明白它是如何工作的,你的解釋對我來說非常有用。 –

+0

現在,你爲什麼谷歌控制檯返回:TypeError:無法讀取屬性'a'的未定義 –

+0

的作品: 'console.dir(grupo [i] .a);' 因爲javascript數組只使用數字索引。 :) –

1

你的意思是這樣的?

for (var key in validation_messages) { 
var obj = validation_messages[key]; 
    for (var prop in obj) { 
     // important check that this is objects own property 
     // not from prototype prop inherited 
     if(obj.hasOwnProperty(prop)){ 
     alert(prop + " = " + obj[prop]); 
     } 
    } 
} 

參考:https://stackoverflow.com/a/921808/1054926

0

GROUPO [I]已經是一個文本對象,所以你有一個錯誤在那裏。此外,你不想看看,直到你的索引是< =的長度。

這裏是一個快速瀏覽一下,你可能會尋找在你的循環是什麼:

for (i=0;i<grupo.length;i++) { 
console.log(i,grupo[i].a); 

}

然而,你將有更多的問題,當你發現的價值「一」是不是你可能會期待什麼。

0

這裏另一種可能的「解決方案」

var text = {}; 
var grupo = []; 

text.a = "texta"; 
text.b = "textb"; 
grupo.push(text); 
text.a = "textc"; 
grupo.push(text); 

for (var i=0;i < grupo.length;i++) { 
    var x = grupo[i]; 
    if (x && x.a){ 
     console.log(x.a);   
    } else { 
     console.log(x);     
    } 
} 
+0

葡萄牙語版本不是非常有效,但thx的提示。 –

+0

是的。我知道。但我們正在改進。 – rdllopes

+0

肯定... ^^ :) –