一個 JavaScript 程式,用於查詢兩個陣列中的不同元素
比如說我們有兩個數字陣列 -
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34];
我們需要編寫一個 JavaScript 函式,它接收兩個這樣的陣列並返回陣列中不屬於兩個陣列的元素。
讓我們為這個函式編寫程式碼 -
示例
程式碼如下 -
const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34]; const unCommonArray = (first, second) => { const res = []; for(let i = 0; i < first.length; i++){ if(second.indexOf(first[i]) === -1){ res.push(first[i]); } }; for(let j = 0; j < second.length; j++){ if(first.indexOf(second[j]) === -1){ res.push(second[j]); }; }; return res; }; console.log(unCommonArray(arr1, arr2));
輸出
控制檯中的輸出如下 -
[ 6, 5, 1 ]
廣告