首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript混淆:对象、数组还是对象数组?

Javascript混淆:对象、数组还是对象数组?
EN

Stack Overflow用户
提问于 2012-09-19 20:36:57
回答 2查看 82关注 0票数 0

我有一个糟糕的编码一天。我就是不明白为什么this code on fiddle没有按照我的期望去做。

代码语言:javascript
复制
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不理解我……

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-19 20:41:41

newList的作用域是addUnique函数,您可以在一个循环中调用该函数8次。每次运行此函数时,都会为masterList (masterList = newList.splice(0);)分配一个新值,以便只在console.log(masterList)中显示最后一个值。

这是你的小提琴的一个固定版本:http://jsfiddle.net/vZNKb/2/

代码语言:javascript
复制
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);
    }
}
票数 2
EN

Stack Overflow用户

发布于 2012-09-19 20:41:25

如果所有元素都不匹配,addUnique中的循环需要遍历所有元素first...then add

相关章节

代码语言:javascript
复制
var matchingRecord = false;
for(j=0;j<masterList.length;j++) {
    if (masterList[j].name == thatObj.name){
        matchingRecord = true;
        break;
    }
}
if(!matchingRecord) newList.push(thatObj);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12494831

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档