迭代对象数组
我有一个像这样的JSON字符串
var json = '{ "Comments": [ { "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0}, { "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0} ] }';
而我正试图迭代这些对象:
var parsedJSON = $.parseJSON(json); var html = ""; for (comment in parsedJSON.Comments) { html += "Id: " + comment.Id; html += "Comment: " + comment.Comment; html += "Name: " + comment.Name; html += "Child: " + comment.Child; html += "
"; }
但是这里for循环的comment
只变为0
和1
,我的意思不是一个对象而只是一个字符串,我怎么能迭代这个数组呢?
var json = '{ "Comments": [{ "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0},{ "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0}] }'; var parsedJSON = $.parseJSON(json), // jsonData should json html = "", comments =parsedJSON.Comments; // keeping reference of parsedJSON and its an Array // Here key will give 0, 1 etc ie. index of array for (var key in comments) { html += "Id: " + comments[key].Id; html += "Comment: " + comments[key].Comment; html += "Name: " + comments[key].Name; html += "Child: " + comments[key].Child; html += "
"; }
演示
你似乎误解了for..in
循环是如何工作的。 comment
将迭代地成为数组的键。 在任何情况下,你不应该在数组上使用for..in
,只能使用对象 – 即使这样也要谨慎。
var l = parsedJSON.Comments.length, i, comment; for( i=0; i
你可以尝试这个:
var JsonData = { "Comments": [ { "Id" : 1,"Comment" : "Test comment","Name" : "Yogesh","Child" : 0}, { "Id" : 2,"Comment" : "Test comment II","Name" : "Yogesh","Child" : 0} ] }; var html = ""; for (var i = 0; i < JsonData.Comments.length; i++) { comment = JsonData.Comments[i]; html += "Id: " + comment.Id; html += " Comment: " + comment.Comment; html += " Name: " + comment.Name; html += " Child: " + comment.Child; html += "
"; } alert(html);
你可以使用$.each
:
var html = ""; $.each(parsedJSON.Comments, function(i, comment) { html += "Id: " + comment.Id; html += "Comment: " + comment.Comment; html += "Name: " + comment.Name; html += "Child: " + comment.Child; html += "
"; }
或者,您可以使用$.map
:
var html = $.map(parsedJSON.Comments, function(comment, i) { return "Id: " + comment.Id + "Comment: " + comment.Comment + "Name: " + comment.Name + "Child: " + comment.Child + "
"; }).join('');
注释包含一个包含两个元素的数组。
{ "Comments" : [ { 1 }, { 2 }] ...
所以你可以用它来访问它
for (var i = 0, len = parsedJSON.Comments.length; i < len; i++) { html += "Id: " + parsedJSON.Comments[i].Id; html += "Comment: " + parsedJSON.Comments[i].Comment; html += "Name: " + parsedJSON.Comments[i].Name; html += "Child: " + parsedJSON.Comments[i].Child; html += "
"; }