最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript recursion counter - Stack Overflow

programmeradmin4浏览0评论

I tried to rewrite this indexOf MDN example to practice recursion

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

This was my solution:

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

It works, but is there anyway to get the count variable inside the function itself? Is it not really a true recursion if I have a count variable outside the function?

I tried to rewrite this indexOf MDN example to practice recursion

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

This was my solution:

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

It works, but is there anyway to get the count variable inside the function itself? Is it not really a true recursion if I have a count variable outside the function?

Share Improve this question asked Mar 28, 2015 at 0:58 WinchenzoMagnificoWinchenzoMagnifico 3,4455 gold badges23 silver badges23 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

What you can do is to return the count value form the method, so if the item is not found you return 0, else you return 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'));

Demo: Fiddle

In a recursive function, if you want to keep a variable around from one "iteration" to the next, then you need to pass it as an argument:

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

However, this is not always necessary, as Arun P Johny's answer illustrates.

发布评论

评论列表(0)

  1. 暂无评论