该函数确定字符串中某些字符的数量。
function countSymbolRec(str, symbol, count) {
if (str[str.length - 1] === symbol) count ++;
if (str.length === 1) return console.log(count);
countSymbolRec(str.slice(0, -1), symbol, count);
}
countSymbolRec("lkjkBBSlkl", "B", 0); // 2
使用
indexOf
!
function countSymbolRec(str, symbol, count, index) {
// Starting at `index`, find the first occurrence of `symbol` in `str`
const symbolIndex = str.indexOf(symbol, index)
// If `str` does not contain `symbol`, return the current `count`
if (symbolIndex === -1) {
return count
}
// Otherwise, go to the next index and search again with an incremented count
return countSymbolRec(str, symbol, count+1, symbolIndex+1)
}
console.log(countSymbolRec("lkjkBBSlkl", "B", 0, 0)); // 2