我试图在不使用for循环的情况下解决以下问题:
"编写一个函数countBs,它将字符串作为唯一的参数,并返回一个数字,指示字符串中有多少大写"B"字符
console.log(countBs("BBC")); // → 2
感谢您的帮助。
这是我迄今为止写的不起作用的代码:
function countBs(word) {
let count = 0
if (word.length == 0) {
return count;
} else {
if (word[word.length - 1] == 'B') {
count++
}
return countBs(word.slice(0, word.length - 1))
}
}
console.log(countBs("BBC"))
在这种情况下,您可以很容易地使用regex:
function countBs(word) {
const matches = word.match(/B/g);
return matches && matches.length || 0;
}
基本上,它g
全局搜索"B"的出现。如果它找到它,它会返回它的长度,如果匹配项是null
,它将返回0。
更简单,表达更少:
function countBs(word) {
return (word.match(/B/g) || []).length;
}