我试图重写这个 indexOf MDN 示例来练习递归
var str = 'To be, or not to be, that is the question.';
var count = 0;
var pos = str.indexOf('e');
while (pos !== -1) {
count++;
pos = str.indexOf('e', pos + 1);
}
console.log(count); // displays 4
这是我的解决方案:
var count = 0;
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return count;
}
else {
count ++;
return countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
它有效,但无论如何都可以在函数本身内部获取计数变量?如果我在函数之外有一个计数变量,这不是真正的递归吗?
最佳答案
在递归函数中,如果要将变量从一次“迭代”保留到下一次,则需要将其作为参数传递:
function countLetters(str, p, count) {
count = count || 0;
var pos = str.indexOf(p);
if (pos == -1) {
return count;
}
else {
return countLetters(str.substr(pos + 1), p, count + 1);
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
// => 4
然而,这并不总是必要的,正如 Arun P Johny 的回答所示。
关于javascript递归计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29312432/