首页 > 开发 > JS > 正文

关于尾递归优化问题

2017-09-05 05:51:32  来源:网友分享

为什么我使用了尾递归优化,还是会产生调用栈溢出的情况呢?
代码如下:

function tcoFactorial(n, index = 1, lastResult = 1) {  if(n === 1) {    return lastResult  } else {    return tcoFactorial(n-1, index + 1, lastResult * (index+1))  }}console.log(tcoFactorial(100000))

错误:

RangeError: Maximum call stack size exceeded

解决方案

V8对尾递归的优化做的并不好,可以尝试根据这篇文章来手动优化尾递归