我有一个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"}
];我要做的就是获取每个I。
我一直在尝试这个
for(x in json[0]){
alert(x.id);
}但是运气不好,谁能给我指个方向?请并感谢您:)
发布于 2012-02-18 02:20:20
在您的示例中,x将为您提供数组的索引,而不是对象。你可以这样做:
for(x in json) {
alert(json[x].id);
}但是要遍历一个数组,最好使用“常规”for循环
for (var i = 0, max = json.length; i < max; i++) {
alert(json[i].id);
}发布于 2012-02-18 02:21:23
任何现代浏览器都能让你轻松做到这一点:
var ids = json.map(function(i) { return i.id; });
// and now you have an array of ids!遗憾的是,“现代”并不包括IE8和更早的版本。
你也可以做“平凡”的表单,它保证在所有浏览器中都能工作。我知道Adam Rackis比我先一步,所以我会支持他的答案,你可能也应该这么做。
发布于 2012-02-18 02:21:46
这是一种可能的解决方案:
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);
}https://stackoverflow.com/questions/9333329
复制相似问题