[英]Javascript confusion: Objects vs. arrays vs. arrays of objects?
我的編碼日很糟糕。 我根本不明白為什么這個小提琴上的代碼沒有按照我的預期行事。
var masterList = new Array();
var templates = new Array();
templates.push({"name":"name 1", "value":"1234"});
templates.push({"name":"name 2", "value":"2345"});
templates.push({"name":"name 3", "value":"3456"});
templates.push({"name":"name 4", "value":"4567"});
templates.push({"name":"name 1", "value":"5678"});
templates.push({"name":"name 2", "value":"6789"});
templates.push({"name":"name 3", "value":"7890"});
templates.push({"name":"name 4", "value":"8901"});
var addUnique = function(thatObj) {
var newList = new Array();
if ( masterList.length == 0 ) {
// add the first element and return
masterList.push(thatObj);
return;
}
for (j=0; j<masterList.length; j++) {
if (masterList[j].name != thatObj.name) {
newList.push(thatObj);
}
}
// store the new master list
masterList = newList.splice(0);
}
for (i=0; i<8; i++) {
addUnique(templates[i]);
}
console.log(masterList);
console.log(masterList.length);
在我的(謙遜)意見中,它應該通過templates數組,用templateArray的每個元素填充masterList,但只導致master數組中的4個元素,因為命名相同的元素應該被“覆蓋”,即沒有被復制到中間數組中,因而沒有被繼承並被新的替換。 相反,我在masterList中獲得了一個條目。
過去的好日子已經過去了,強類型語言。 指針。 嘆。 我只是不知道javascript正在制造什么樣的混亂(好吧,我當然弄得一團糟)但是我責怪JS不理解我......
newList
的作用域為addUnique
函數,您可以在循環中調用8次。 每次運行此函數時,都會為masterList( masterList = newList.splice(0);
)分配一個新值,因此只有最后一個值顯示在console.log(masterList)
。
這是你的小提琴的固定版本: http : //jsfiddle.net/vZNKb/2/
var addUnique = function(thatObj) {
if ( masterList.length == 0 ) {
// add the first element and return
masterList.push(thatObj);
return;
}
var exists = false;
for (var j = 0; j < masterList.length; j++) {
if (masterList[j].name == thatObj.name) {
exists = true;
break;
}
}
if (!exists) {
masterList.push(thatObj);
}
}
你在addUnique
中的循環需要先遍歷所有元素然后添加,如果沒有元素匹配
相關部分
var matchingRecord = false;
for(j=0;j<masterList.length;j++) {
if (masterList[j].name == thatObj.name){
matchingRecord = true;
break;
}
}
if(!matchingRecord) newList.push(thatObj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.