我有两个阵列。
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
我想检查“addFrom”数组中的第一项是否已经在“addTo”数组中。
如果“addTo”数组没有“addFrom”数组中的第一项,我想将此项目推送到“addTo”数组。
但是,如果“addFrom”数组中的第一项已经在“addTo”数组中,我想转到“addFrom”数组中的第二项,并执行相同的操作直到找到该项在“addFrom”数组中的“addFrom”数组中,然后将其推送到“addTo”数组。我想只在“addTo”数组中添加一个项目。
因此,我希望“addTo”数组看起来像这样:
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry", "banana"];
我如何在JavaScript中执行此操作?
答案 0 :(得分:2)
如果一个项目不在addTo
数组中,您可以使用Array#some()
并停止迭代。
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"],
addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
addFrom.some(function (a) {
if (!~addTo.indexOf(a)) {
addTo.push(a);
return true;
}
});
document.write('<pre> ' + JSON.stringify(addTo, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:1)
一个简单的循环似乎是最好的方法(我使用过while
)。
var i = -1, len = addFrom.length;
while (++i < len) {
if (addTo.indexOf(addFrom[i]) === -1) {
addTo.push(addFrom[i]);
break;
}
}
答案 2 :(得分:1)
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
for(var i = 0; i < addFrom.length; i++){
if(addTo.indexOf(addFrom[i]) === -1 ){
addTo.push(addFrom[i]);
break;
}
}
答案 3 :(得分:0)
https://jsfiddle.net/povvx8hg/
var addFrom = ["orange", "banana", "watermelon", "lemon", "peach"];
var addTo = ["pear", "tangerine", "grape", "orange", "blueberry"];
for (i = 0; i < addFrom.length; i++) {
if(addTo.indexOf(addFrom[i]) != -1) {
console.log("Exist");
} else {
addTo.push(addFrom[i]);
}
}
console.log(addTo);
答案 4 :(得分:0)
容易羞怯
for (index = 0; index < addFrom.length; ++index) {
if (addTo.indexOf(addFrom[index]) === -1){
addTo.push(addFrom[index]);
break;
}
}
答案 5 :(得分:-1)
您可以使用forEach
addFrom.forEach(function(v,i){
if(addTo.indexOf(v)<0)
addTo.push(v);
}
)