JS 陣列中數字和字串數字表示之間的差異


問題

我們要求編寫一個 JavaScript 函式,該函式採用數字的混合陣列和整數的字串表示形式。

我們的函式應該將字串整數相加,然後從非字串整數的總和中減去它。

示例

以下是程式碼 −

 實際演示

const arr = [5, 2, '4', '7', '4', 2, 7, 9];
const integerDifference = (arr = []) => {
   let res = 0;
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(typeof el === 'number'){
         res += el;
      }else if(typeof el === 'string' && +el){
         res -= (+el);
      };
   };
   return res;
};
console.log(integerDifference(arr));

輸出

以下是控制檯輸出 −

10

更新於: 2021-04-19

307 次閱讀

開啟你的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.