在字串JavaScript中查詢空格數


我們需要編寫一個 JavaScript 函式,該函式接受一個包含空格的字串。該函式應簡單地計算該字串中存在的空格數。

例如 -

如果輸入字串是 -

const str = 'this is a string';

那麼輸出應該是 -

const output = 4;

示例

const str = 'this is a string';
const countSpaces = (str = '') => {
   let count = 0;
   for(let i = 0;
   i < str.length; i++){
      const el = str[i];
      if(el !== ' '){
         continue; };
         count++; };
      return count;
};
console.log(countSpaces(str));

輸出

這將生成以下輸出 -

4

更新於:2020 年 11 月 25 日

1000+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

立即開始
廣告