我需要遍历来自服务器的JSON数组。它看起来完全像这样:
[{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}]
我在这里找到了一些建议,但它们似乎都不适合我。有没有简单的方法可以获得所有这些价值?
答案 0 :(得分:1)
var arr = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}];
for(var i = 0; l = arr.length; i< l; i+=1)
{
console.log(arr[i].username); // log username
}
另一种选择:
arr.forEach(function(i) {
console.log(i.username)
});
答案 1 :(得分:0)
var data = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}],
usernames = [];
for(var i=0; i<data.length; i++) {
usernames.push(data[i].username);
}
答案 2 :(得分:0)
试试这个:
var o = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}];
for(var i = 0; i < o.length ; i++)
for(var j in o[i])
alert(j + ": " + o[i][j]);
答案 3 :(得分:0)
如果您不需要IE&lt; 9兼容性,则可以使用Array.prototype.map()
var arr = [{"username":"betontester"},{"username":"kuesst"},{"username":"master_pat"},{"username":"olli"},{"username":"test15"},{"username":"test20140216"},{"username":"test789"},{"username":"tester100"},{"username":"tobi"}],
usernames = arr.map(function(item) {
return item.username;
});