这是尾调用吗? (Javascript)

2024-03-26

假设您有一个递归函数,例如:

Blah.prototype.add = function(n) {
    this.total += n;
    this.children.forEach(function(child) {
        child.add(n);
    });
};

Is the child.add()尾部呼叫?如果不是可以这样写吗?


是的,这是一个尾调用:

function(child) {
    child.add(n);
// ^ tail
}

然而这里没有尾递归,因为它不是直接递归调用。

Also this.children.forEach(…)是一个尾部调用add method.

但是,在本机中调​​用回调forEach方法可能不是尾部调用优化的(而且除了最后一个之外的所有方法都不能优化)。您可以通过将函数重写为来强制它

Blah.prototype.add = function(n) {
    "use strict";
    this.total += n;
    let l = this.children.length;
    if (!l--)
        return;
    for (let i=0; i<l; i++)
        this.children[i].add(n);
    this.children[i].add(n); // tail-recursion
};

请注意,如果您不这样做,这些尾部调用都不会得到优化return他们的结果。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这是尾调用吗? (Javascript) 的相关文章

随机推荐