從字串中求和 - JavaScript


我們需要編寫一個 JavaScript 函式,它接受一個包含一些單數字符串,而該函式應返回字串中所有數字的總和。

假設以下內容是我們的數字字串 -

const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';

示例

我們來編寫此程式碼 -

const str = 'gdf5jhhj3hbj4hbj3jbb4bbjj3jb5bjjb5bj3';
const sumStringNum = str => {
   const strArr = str.split("");
   let res = 0;
   for(let i = 0; i < strArr.length; i++){
      if(+strArr[i]){
         res += +strArr[i];
      };
   };
   return res;
};
console.log(sumStringNum(str));

輸出

控制檯中的輸出 -

35

更新日期: 15-Sep-2020

750 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.