使用 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
廣告