Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

javascript - JavaScript通过json数组循环?(JavaScript loop through json array?)

I am trying to loop through the following json array:(我试图遍历以下json数组:)

{ "id": "1", "msg": "hi", "tid": "2013-05-05 23:35", "fromWho": "hello1@email.se" }, { "id": "2", "msg": "there", "tid": "2013-05-05 23:45", "fromWho": "hello2@email.se" } And have tried the following(并尝试了以下) for (var key in data) { if (data.hasOwnProperty(key)) { console.log(data[key].id); } } But for some reason i am only getting the first part, id 1 values.(但是由于某种原因,我只得到第一部分,id 1值。) Any ideas?(有任何想法吗?)   ask by Alosyius translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your JSON should look like this:(您的JSON应该如下所示:)

var json = [{ "id" : "1", "msg" : "hi", "tid" : "2013-05-05 23:35", "fromWho": "hello1@email.se" }, { "id" : "2", "msg" : "there", "tid" : "2013-05-05 23:45", "fromWho": "hello2@email.se" }]; You can loop over the Array like this:(您可以像这样遍历数组:) for(var i = 0; i < json.length; i++) { var obj = json[i]; console.log(obj.id); } Or like this (suggested from Eric) be careful with IE support(或像这样(由Eric建议)应注意IE支持) json.forEach(function(obj) { console.log(obj.id); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...