我有一个JSON响应对象,如:
{ “1”: “不存在”, “2”: “卖”, “3”: “卖”, “4”: “卖”, “5”: “卖”, “6”:“出售”, “7”: “卖”, “8”: “卖”, “9”: “售出”}
如何遍历所有对象的成员变量?
响应是可变的。它可能像:
{ “5”: “不存在”, “23”: “卖”, “24”: “卖”, “26”: “卖”, “29”: “卖”, “41”:“卖”, “42”: “卖”, “42”: “卖”, “42”: “售出”}
json查询:
$.getJSON(myurl + '?action=21' + '&token=' + token + '&id=' + total + '&sell=1',
function(data){
for (var i = '0'; i < reply.length; i++) {
var obj = data[i][2];
alert(obj);
}
})
答案 0 :(得分:4)
在Javascript中,for in
循环遍历对象的键。所以你想要这个:
var i;
for (i in data) {
if (data.hasOwnProperty(i)) {
alert(data[i]);
}
}
使用此样式的循环时,建议使用hasOwnProperty(i)
。对于像这样的简单普通物体,它并非完全必要,但它也是一个很好的习惯。
答案 1 :(得分:0)
小提琴 - http://jsfiddle.net/tariqulazam/qAWbW/
var data = {"1":"absent","2":"sold","3":"sold","4":"sold","5":"sold","6":"sold","7":"sold","8":"sold","9":"sold"};
for (var key in data) {
console.log(key + '----' + data[key]);
}
这应该对你有用
$.getJSON(myurl + '?action=21' + '&token=' + token + '&id=' + total +
'&sell=1',
function(data){
for (var key in data) {
console.log(key + '----' + data[key]);
}
});
答案 2 :(得分:0)
使用for
var data = {
"1": "absent",
"2": "sold",
"3": "sold",
"4": "sold",
"5": "sold",
"6": "sold",
"7": "sold",
"8": "sold",
"9": "sold"
};
for (key in data) {
console.log(data[key])
};