我有一个 jQuery.each 循环遍历具有三组数据的 JSON 对象,但由于某种原因,循环输出 13 个对象而不是 3 个,其中 10 个是空的。这是我的代码:
var teammates_info=[];
var teammate_json={"teammates":[{"id":"12","first_name":"Bob","last_name":"Johnson","user_img":"","status":"offline","new_messages":"0"},{"id":"9","first_name":"John","last_name":"Doe","user_img":"","status":"offline","new_messages":"0"},{"id":"10","first_name":"test","last_name":"test","user_img":"","status":"offline","new_messages":"0"}]};
jQuery.each(teammate_json.teammates,function(index,teammate){
teammates_info[teammate.id]=[{"first_name":teammate.first_name,"last_name":teammate.last_name,"user_img":teammate.user_img,"status":teammate.status,"new_messages":teammate.new_messages}];
});
console.log(teammates_info.length); //outputs 13 not 3
如果我这样做了document.write(teammates_info);
,,,,,,,,,,[object Object],[object Object],,[object Object]
那么您可以看到正在创建的所有空数组元素。
我正在尝试输出一个对象数组,这样我可以稍后在我的代码中引用队友的数据teammates_info[12]["first_name"]
,但我很难理解为什么要创建 13 个数组元素而不是 3 个。