【问题标题】:Javascript loop an arrayJavascript循环一个数组
【发布时间】:2012-02-17 18:18:05
【问题描述】:

我有一个这样写的 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"}
];

我要做的是获取每个 ID。

我一直在尝试这个

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

但是运气不好,有人能指出我正确的方向吗?请和谢谢你:)

【问题讨论】:

标签: javascript arrays for-loop


【解决方案1】:

x 在您的示例中为您提供数组的 索引,而不是对象。你可以这样做:

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

但是要遍历数组,最好使用“常规” for 循环

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

【讨论】:

  • 太棒了,这正是我想要的。谢谢
【解决方案2】:

任何现代浏览器都可以让您轻松完成:

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

遗憾的是,“现代”不包括 IE 8 及更早版本。

您也可以使用“普通”表单,保证在所有浏览器中都可以使用。我看到 Adam Rackis 击败了我,所以我会投票赞成他的回答,你也应该这样做。

【讨论】:

  • +1 - 很好 - 我真的需要更多地开始使用这些 ES5 方法。还有Sadly, "modern" does not include IE 8ftw
【解决方案3】:

这是一种可能的解决方案:

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);
}

【讨论】:

    【解决方案4】:

    JavaScript 中的 for(x in y) 循环为您提供该数组中的索引(例如,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]
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-14
      • 1970-01-01
      • 2013-03-04
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2018-09-07
      相关资源
      最近更新 更多