弑天下
我假设你正在比较一个普通的数组。如果没有,则需要将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"));如果您不关心向后兼容性,更好的解决方案是使用过滤器。但是,这个解决方案仍然有效。
交互式爱情
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之前不可用。