3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個贊
我假設(shè)你正在比較一個普通的數(shù)組。如果沒有,則需要將for循環(huán)更改為for ... in循環(huán)。
function arr_diff (a1, a2) {
var a = [], diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
console.log(arr_diff(['a', 'b'], ['a', 'b', 'c', 'd']));
console.log(arr_diff("abcd", "abcde"));
console.log(arr_diff("zxc", "zxc"));
如果您不關(guān)心向后兼容性,更好的解決方案是使用過濾器。但是,這個解決方案仍然有效。

TA貢獻(xiàn)1712條經(jīng)驗(yàn) 獲得超3個贊
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
////////////////////
// Examples
////////////////////
[1,2,3,4,5,6].diff( [3,4,5] );
// => [1, 2, 6]
["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);
// => ["test5", "test6"]
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
////////////////////
// Examples
////////////////////
var dif1 = [1,2,3,4,5,6].diff( [3,4,5] );
console.log(dif1); // => [1, 2, 6]
var dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);
console.log(dif2); // => ["test5", "test6"]
注意 indexOf和filter在ie9之前不可用。

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個贊
到目前為止,這是使用jQuery獲得您正在尋找的結(jié)果的最簡單方法:
var diff = $(old_array).not(new_array).get();
diff
現(xiàn)在包含了old_array
不存在的內(nèi)容new_array
添加回答
舉報(bào)