0
我有一個jQuery.each循環迭代通過具有三組數據的JSON對象,但出於某種原因,循環輸出13個對象而不是3個,其中10個是空的。這裏是我的代碼:jQuery.each循環向數組添加空值
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
http://jsfiddle.net/7bZtV/3/使用推(),不要設置你的具體指標進行排列。否則,請使用非索引對象,而不是數組 –
@ A.Wolff我需要設置一個特定索引,以便我可以在代碼中稍後通過隊友ID引用它。 – BWDesign
剛剛編輯我以前的評論,所以使用一個對象,而不是一個數組 –