JavaScript递归计数器

4

我尝试重写这个MDN的indexOf实例来练习递归

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'));

它能够运行,但是有没有办法在函数本身内获取计数变量?如果我在函数外面有一个计数变量,那么这真的算递归吗?

2个回答

7
你可以返回该方法的计数值,如果没有找到该项,则返回0,否则返回1 + 递归调用的值
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'));

Demo: Fiddle


7
在递归函数中,如果您想要在每一次“迭代”之间保留某个变量,则需要将其作为参数传递:
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的回答所示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接