JavaScript fibonacci using recursion

扶醉桌前 提交于 2019-12-12 14:39:46

问题


Trying to get my fibonacci sequence to work using recursion but am running into the error 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.


回答1:


The behaviour of ++ is different in postfix and prefix notation.

From MDN:

If used postfix, with operator after operand (for example, x++), then it returns the value before incrementing.

If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.

This means that you are always passing count before incrementing it, resulting in stack overflow.

To solve your problem, change

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

To

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



回答2:


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.




回答3:


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.

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


来源:https://stackoverflow.com/questions/36016580/javascript-fibonacci-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!