我試圖在javascript中比較兩個列表。如果ListA中存在不在ListB中的東西 - 我想將它推到ListB。如果它存在,我不想做任何事情。列表中的項目是字符串。測試兩個字符串是否相等給出奇數結果
當我檢查一個字符串是否等於另一個字符串時,我得到了非常奇怪的結果。這裏是我的JS:
function assignColor() {
var test = ["JackBean", "MrX", "SuperMan", "BobHemsworth", "SomeoneElse", "AnotherSomeone"]
var list_existing = ["JackBean", "MrX", "SuperMan", "BobHemsworth"];
length_of_existing = list_existing.length;
i=0;
while (i < test.length) {
var person_in_list = test[i]
for (var j=0; j <= parseInt(length_of_existing); j++) {
if (person_in_list === list_existing[j]) {
console.log("equal");
}
else {
console.log("not equal");
list_existing.push(person_in_list);
}
}
++i;
}
console.log(list_existing);
}
我得到list_existing的輸出如下:
[ 「JackBean」, 「MRX」, 「超人」, 「BobHemsworth」, 「JackBean」,「 JackBean「,」MrX「,」SuperMan「,」BobHemsworth「]
這可能是令人沮喪的簡單。但我嘗試了幾種不同的組合來成功比較兩個字符串....失敗。
這個作品真的很好謝謝! –
不客氣! @RuthYoung – baao