使用 JavaScript 統計字母中的環數


問題

我們需要編寫一個 JavaScript 函式來輸入一個英文字母的字串。我們的函式應該統計字串中出現的環數。

“O”、“b”、“p”、“e”、“A”等都有一個環,而“B”有兩個環

示例

以下為程式碼示例 −

 線上演示

const str = 'some random text string';
function countRings(str){
   const rings = ['A', 'D', 'O', 'P', 'Q', 'R', 'a', 'b', 'd', 'e', 'g', 'o', 'p', 'q'];
   const twoRings = ['B'];
   let score = 0;
   str.split('').map(x => rings.includes(x)
   ? score++
   : twoRings.includes(x)
   ? score = score + 2
   : x
   );
   return score;
}
console.log(countRings(str));

輸出

7

更新日期:2021-04-17

143 次瀏覽

開啟你的 職業生涯

完成本課程並獲得認證

開始
廣告