3 回答
TA贡献1818条经验 获得超8个赞
我假设你正在比较一个普通的数组。如果没有,则需要将for循环更改为for ... in循环。
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"));
如果您不关心向后兼容性,更好的解决方案是使用过滤器。但是,这个解决方案仍然有效。
TA贡献1712条经验 获得超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贡献1802条经验 获得超5个赞
到目前为止,这是使用jQuery获得您正在寻找的结果的最简单方法:
var diff = $(old_array).not(new_array).get();
diff
现在包含了old_array
不存在的内容new_array
添加回答
举报