JavaScript 中兩個 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 difference = (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(difference(arr1, arr2));

輸出

控制檯中的輸出將是:

[ 6, 5, 1 ]

更新於:20-Oct-2020

120 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
Advertisement
© . All rights reserved.