Javascript JSON foreach不工作
我有以下JSON代码:Javascript JSON foreach不工作,javascript,jquery,json,Javascript,Jquery,Json,我有以下JSON代码: { "chat": [ { "username": "demo", "text": "hi man", "time": "1380167419" }, { "username": "admin", "text": "hi", "time": "1380167435"
{
"chat": [
{
"username": "demo",
"text": "hi man",
"time": "1380167419"
},
{
"username": "admin",
"text": "hi",
"time": "1380167435"
},
{
"username": "demo",
"text": "this works flawless now.",
"time": "1380167436"
},
{
"username": "demo",
"text": "we basically done/",
"time": "1380167443"
}
]
}
当我跑步时:
var codes = JSON.parse(history); //history is the above JSON.
$.each(codes, function(key, value){
alert(value.chat.username);
});
它没有发出任何警报,一直告诉我value.chat.username未定义
我哪里做错了?您不需要解析JSON。它已经是一个JSON对象了
$.each(history.chat, function(key, value){
alert(value.username);
});
您还必须迭代聊天数组并正确引用其项。这就是。。。因为没有定义.chat
var codes = JSON.parse(history); //history is the above JSON.
$.each(codes.chat, function(key, value){
alert(value.username);
});
这一次,您在
value.chat
中定义了一个对象数组。您需要先选择一个数组元素,然后才能查看username
。正确的形式是value.chat[n].username
,其中n
是数组中的索引。如果要在聊天
对象中遍历数组,需要执行以下操作:
$.each(codes.chat, function(key, value){
alert(value.username);
});
请注意,我们现在正在迭代
聊天
,因此我们可以直接处理每个聊天
元素中的属性。我们不明白为什么会有这些反对票……但感谢大家的帮助。