pix*_*ike 6 javascript tail-call-optimization
你有一个递归函数,如:
Blah.prototype.add = function(n) {
this.total += n;
this.children.forEach(function(child) {
child.add(n);
});
};
Run Code Online (Sandbox Code Playgroud)
是child.add()尾巴吗?如果不能这样写的话呢?
是的,这是一个尾调用:
\n\nfunction(child) {\n child.add(n);\n// ^ tail\n}\nRun Code Online (Sandbox Code Playgroud)\n\n然而这里没有任何东西是尾递归的,因为它不是直接递归调用。
\n\n也是方法this.children.forEach(\xe2\x80\xa6)内的尾部调用add。
但是,本机方法中回调的调用forEach可能不是尾部调用优化的(并且除了最后一个之外的所有调用都不能优化)。您可以通过将函数重写为来强制它
Blah.prototype.add = function(n) {\n "use strict";\n this.total += n;\n let l = this.children.length;\n if (!l--)\n return;\n for (let i=0; i<l; i++)\n this.children[i].add(n);\n this.children[i].add(n); // tail-recursion\n};\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,如果您不了解这些尾部调用的return结果,则这些尾部调用都不会得到优化。
| 归档时间: |
|
| 查看次数: |
305 次 |
| 最近记录: |