我有一个糟糕的编码一天。我就是不明白为什么this code on fiddle没有按照我的期望去做。
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不理解我……
发布于 2012-09-19 20:41:41
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);
}
}发布于 2012-09-19 20:41:25
如果所有元素都不匹配,addUnique中的循环需要遍历所有元素first...then add
相关章节
var matchingRecord = false;
for(j=0;j<masterList.length;j++) {
if (masterList[j].name == thatObj.name){
matchingRecord = true;
break;
}
}
if(!matchingRecord) newList.push(thatObj);https://stackoverflow.com/questions/12494831
复制相似问题