Win*_*ico 2 javascript recursion
我试图重写这个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
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案:
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'));
Run Code Online (Sandbox Code Playgroud)
它有效,但无论如何都要在函数内部获取count变量?如果我在函数外部有一个count变量,它真的不是真正的递归吗?
您可以做的是从方法返回计数值,因此如果未找到该项目,则返回 0,否则返回 1 + value-of-recursive-call
function countLetters(str, p) {
var pos = str.indexOf(p);
if (pos == -1) {
return 0;
} else {
return 1 + countLetters(str.substr(pos + 1), p)
}
}
console.log(countLetters('To be, or not to be, that is the question.', 'e'));
Run Code Online (Sandbox Code Playgroud)
演示:小提琴
在递归函数中,如果要保持变量从一个"迭代"到下一个,那么您需要将其作为参数传递:
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
Run Code Online (Sandbox Code Playgroud)
然而,正如Arun P Johny的回答所示,这并不总是必要的.