2012-02-17 65 views
1

我寫這樣的JavaScript數組...的Javascript循環數組

var json = [ 
    {"id":"1", "title":"Test 1", "comment":"This is the first test"}, 
    {"id":"2", "title":"Test 2", "comment":"This is the second test"} 
]; 

什麼,我試圖做的是讓IDS中的每一個。

我一直在嘗試這種

for(x in json[0]){ 
    alert(x.id);   
} 

,但沒有運氣,有人可以點我在正確的方向?請和謝謝你:)

+0

[與字符串數組輸出索引迴路...](可能重複http://stackoverflow.com/questions/ 7480020/for-in-loop-with-string-array-outputs-indices) – 2012-02-17 18:21:58

+0

您可能會發現閱讀['for ... in'文檔](https://developer.mozilla.org/ EN/JavaScript的/參考/語句/對...的)。 – 2012-02-17 18:22:38

回答

5

x在你的例子是給你索引你的數組,而不是對象。你可以這樣做:

for(x in json) { 
    alert(json[x].id);   
} 

而是通過你真的有一個「常規」更好的for循環數組循環

for (var i = 0, max = json.length; i < max; i++) { 
    alert(json[i].id); 
} 
+0

非常棒的人,這正是我一直在尋找的。謝謝 – user979331 2012-02-17 18:32:40

+0

@ user1193385 - 我的榮幸。很高興它的工作。 – 2012-02-17 18:35:24

4

任何現代的瀏覽器可以讓你輕鬆做到這一點:

var ids = json.map(function(i) { return i.id; }); 
// and now you have an array of ids! 

不幸的是,「現代」不包括IE 8及更早版本。

你也可以做「世俗」的形式,它可以保證在所有瀏覽器中都能正常工作。雖然我看到Adam Rackis已經打敗了我,所以我會提高他的答案,你也應該這樣做。

+0

+1 - 很好 - 我真的需要更多地開始使用這些ES5方法。而且「可悲的是,」現代「不包括IE 8 ftw – 2012-02-17 18:27:31

+0

我也認爲這個想法 – user979331 2012-02-17 18:39:58

1

這是一個可能的解決方案:

var json = [{"id":"1","title":"Test 1","comment":"This is the first test"},{"id":"2","title":"Test 2","comment":"This is the second test"}]; 

for (var i = 0, len = json.length; i < len; i++) { 
    alert(json[i].id); 
} 
1

for(x in y)一個循環在JavaScript給你索引數組中(例如,以便x[y]給你當前元素)。

通過在JavaScript中一個陣列的兩個適當的方法來循環是:

for(x = 0; x < y.length; x++) { // (this can only loop through arrays) 
    // do something with y[x] 
} 
for(x in y) { // (this can loop through objects too) 
    // do something with y[x] 
}