javascript递归计数器

时间:2015-03-28 00:58:59

标签: 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

这是我的解决方案:

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

它有效,但无论如何都要在函数内部获取count变量?如果我在函数外部有一个count变量,它真的不是真正的递归吗?

2 个答案:

答案 0 :(得分:5)

在递归函数中,如果要将变量从一个“迭代”保持到下一个“迭代”,则需要将其作为参数传递:

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的回答所示。

答案 1 :(得分:3)

您可以做的是从方法返回计数值,因此如果找不到该项,则返回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'));

演示:Fiddle