我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
我有以下JSON结构:
[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]
我如何使用JavaScript迭代它?
当前回答
从http://www.w3schools.com复制和粘贴,不需要JQuery开销。
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
结果:无名氏25人
其他回答
取自jQuery文档:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
mootools的例子:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
var arr = [{" id ":“10”,“类”:" child-of-9 "}, {" id ":“11”,“类”:“child-of-10”}); For (var I = 0;I < arrr .length;我+ +){ 文档。写("<br><br>数组索引:" + i); Var obj = arr[i]; For (var key in obj){ Var值= obj[key]; 文档。Write ("<br> - " + key + ": " + value "); } }
注意:for-in方法对于简单对象很酷。与DOM对象一起使用不是很明智。
从http://www.w3schools.com复制和粘贴,不需要JQuery开销。
var person = {fname:"John", lname:"Doe", age:25};
var text = "";
var x;
for (x in person) {
text += person[x];
}
结果:无名氏25人
对于嵌套对象,可以通过递归函数检索:
function inside(events)
{
for (i in events) {
if (typeof events[i] === 'object')
inside(events[i]);
else
alert(events[i]);
}
}
inside(events);
其中as events是json object。