javascript递归计数器

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

它有效,但无论如何都可以在函数本身内部获取计数变量?如果我在函数之外有一个计数变量,这不是真正的递归吗?

最佳答案

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

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/

相关文章:

javascript - 从 iframe 发布到墙上后重定向

javascript - 为什么我的迷你按钮在 jQuery Mobile 的 ListView 中这么大?

recursion - Clojure 中的非尾递归匿名函数

c++ - 使用递归的二维链表复制构造函数

javascript - onPress 事件不适用于 React Native 中的 View 、图像、可触摸不透明度

javascript - 如何使用jquery删除特殊字符前的逗号

python - 递归查找文件夹中文件的最后一次编辑

Levy C曲线的Javascript递归实现

haskell - 为什么这个函数的类型是(a -> a) -> a?

javascript - 如何从 Form Extjs 6.0.2 获取 DisplayField 的值?