2012-09-19 71 views
0

我的编码日不好。我根本不明白为什么this code on fiddle没有达到我期望的效果。Javascript confusion:对象与数组还是对象数组?

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); 

在我(谦虚)看来,它应该通过模板阵列,填补了templateArray的每个元素的masterList,但只造成主阵列中的4个元素,因为这被命名为相同的那些应该被“覆盖”,即不复制到中间数组中,因此不会被继承和替换。相反,我在masterList中获得一个条目。

哪里有美好的过去,强类型的语言。指针。叹。我只是没有得到什么样的混乱JavaScript正在做(当然,我正在混乱当然),但我责备JS不理解我...

回答

2

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); 
    } 
} 
0

你的循环在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);