JavaScript 中所有未重複元素的總和


假設,我們有一個這樣的數字陣列 −

const arr = [14, 54, 23, 14, 24, 33, 44, 54, 77, 87, 77, 14];

我們需要編寫一個 JavaScript 函式,該函式接受一個這樣的陣列,並統計陣列中僅出現過一次的所有元素之和 −

例如

上面提到的陣列的輸出將為 −

356

以下程式碼將為 −

const arr = [14, 54, 23, 14, 24, 33, 44, 54, 77, 87, 77, 14];
const nonRepeatingSum = arr => {
   let res = 0;
   for(let i = 0; i < arr.length; i++){
      if(i !== arr.lastIndexOf(arr[i])){
         continue;
      };
      res += arr[i];
   };
   return res;
};
console.log(nonRepeatingSum(arr));

以下是控制檯上的輸出 −

30

更新於:2020 年 10 月 9 日

380 次瀏覽

開啟你的 職業

完成課程取得認證

開始
廣告
© . All rights reserved.