下面是用註釋解釋發生了什麼和樣本輸出
var arr1 = [1,2,'foo','bar'];
var arr2 = [2,3,'foo'];
var diff = diff(arr1, arr2);
console.log(diff); // ["1", "3", "bar"]
function diff(arr1, arr2) {
var newArr = [];
var a=[];
// Loop through arr1
// set the value of each entry as an index in array `a`
// set the value of the entry in `a` to true
for(var i=0;i<arr1.length;i++)
a[arr1[i]]=true;
// console.log(a); // [1: true, 2: true, foo: true, bar: true]
// Loop through arr2
// check if each entry exists as an index in array `a`
// if it does, delete the value from array `a`
// if not, set the value of the entry in `a` to true
for(var j=0;j<arr2.length;j++)
if(a[arr2[j]])
delete a[arr2[j]];
else
a[arr2[j]]=true;
// console.log(a); // [1: true, 3: true, bar: true]
// put all of the indexs of array `a` to values in `newArr`
for(var k in a)
newArr.push(k);
return newArr;
}
http://jsfiddle.net/daCrosby/6rcf1j72/
從代碼清理的一面,如果你想有一個較短的功能,你可以使用類似一個代碼其中:
console.log("Looping", diffLoop); // [1, "bar", 3]
console.log("Filtering", diffFilter); // [1, "bar", 3]
function diffLoop(arr1, arr2){
var arr = arr1;
for(var j=0; j<arr2.length; j++)
if(arr.indexOf(arr2[j]) > -1)
arr.splice(arr.indexOf(arr2[j]), 1);
else
arr.push(arr2[j]);
return arr;
}
function diffFilter(arr1, arr2){
var arr = arr1.concat(arr2);
return arr.filter(function(i) {
var in1 = arr1.indexOf(i) < 0;
var in2 = arr2.indexOf(i) < 0;
return (in1 || in2) && !(in1 && in2);
});
}
http://jsfiddle.net/daCrosby/6rcf1j72/1/
C和C++都有等價的構造,您聲稱知道這些構造。 – Blindy
@Bindy:在其他C,C++中,我們通常在'[]'中提供數組的索引。奇怪的是看到一個數組作爲另一個數組中的索引。 –
他們是索引。我沒有感到困惑,你用'arr1 [i]'爲'a'編制索引,這與它們的等價C和C++結構完全相同。 – Blindy