我有一个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. / p>