简体   繁体   English

JavaScript fibonacci使用递归

[英]JavaScript fibonacci using recursion

Trying to get my fibonacci sequence to work using recursion but am running into the error maximum callstack exceeded . 试图让我的斐波纳契序列使用递归工作,但遇到错误maximum callstack exceeded

Code: 码:

var genFib = function(count, limit, fibArray) {
  if (count === undefined || count === null) {
    var count = 0;
  }

  if (fibArray === undefined || fibArray === null) {
    var fibArray = [0, 1];
  }

  if (count === limit) {
    console.log(fibArray);
    return fibArray;
  }

  var pushFibNo = function(fibArray) {
    fibArray.push(fibArray[fibArray.length - 1] + fibArray[fibArray.length - 2]);
    return fibArray;
  };

  // console.log(count++);
  // console.log(limit);
  // console.log(pushFibNo(fibArray));

  return genFib(count++, limit, pushFibNo(fibArray));

};

genFib(null, 50, null);

The three console.logs towards the bottom are logging out correct numbers, but I'm still getting the maximum callstack error. 底部的三个console.logs正在记录正确的数字,但我仍然遇到maximum callstack错误。

The behaviour of ++ is different in postfix and prefix notation. ++的行为在后缀和前缀表示法中是不同的。

From MDN : 来自MDN

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing. 如果使用postfix,操作符后面的运算符(例如,x ++),则它在递增之前返回值。

If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing. 如果在操作数之前使用带有运算符的前缀(例如,++ x),则在递增后返回该值。

This means that you are always passing count before incrementing it, resulting in stack overflow. 这意味着在递增count之前总是会传递count ,从而导致堆栈溢出。

To solve your problem, change 要解决您的问题,请更改

return genFib(count++, limit, pushFibNo(fibArray));

To

return genFib(++count, limit, pushFibNo(fibArray));
if (count === undefined || count === null) {
    var count = 0;
}

you have declared "count" again. 你又宣布了“数”。 this overrides the count parameter and the if(count === limit) is never called. 这会覆盖count参数,并且永远不会调用if(count === limit)。

The problem was that you was using the postincrement in this line 问题是你在这一行使用了后增量

return genFib(count++, limit, pushFibNo(fibArray));

Then you always called the fucntion with the same value for "count", if you use the preoperator should works. 然后你总是用“count”的相同值调用fucntion,如果你使用preoperator应该有效。

return genFib(++count, limit, pushFibNo(fibArray));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM