JavaScript使用尾递归没效果?

我学习函数式编程需要用到尾递归。发现没起到作用。我的代码是不是有错误,还是谷歌浏览器不支持。

function currying(fn, n) {
  return function (m) {
    return fn.call(this, m, n);
  };
}

function tailFactorial(n, total) {
  "use strict";
  if (n === 1) {
    console.trace()
    return total
  };
  return tailFactorial(n - 1, n * total);
}

const factorial = currying(tailFactorial, 1);

factorial(5) // 120

我这样写代码发现浏览器控制台是这样的

console.trace
tailFactorial    @    index.js:751
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
tailFactorial    @    index.js:754
(anonymous)    @    index.js:743
(anonymous)    @    index.js:759
112    @    index.js:788
__webpack_require__    @    vendor.js:55
51    @    index.js:3679
__webpack_require__    @    vendor.js:55
92    @    index.js:4233
__webpack_require__    @    vendor.js:55
85    @    index.js:4034
__webpack_require__    @    vendor.js:55
81    @    index.js:3988
__webpack_require__    @    vendor.js:55
webpackJsonpCallback    @    vendor.js:26
(anonymous)    @    index.js:1

按照尾部优化应该是这样的

console.trace
tailFactorial    @    index.js:751
(anonymous)    @    index.js:743
(anonymous)    @    index.js:759
112    @    index.js:788
__webpack_require__    @    vendor.js:55
51    @    index.js:3679
__webpack_require__    @    vendor.js:55
92    @    index.js:4233
__webpack_require__    @    vendor.js:55
85    @    index.js:4034
__webpack_require__    @    vendor.js:55
81    @    index.js:3988
__webpack_require__    @    vendor.js:55
webpackJsonpCallback    @    vendor.js:26
(anonymous)    @    index.js:1

请问这是为什么?

阅读 3.2k
1 个回答

目前除了 Safari 都不支持尾递归

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题