简体   繁体   English

Javascript尾递归而不是循环

[英]Javascript tail recursion instead of loop

In one of Douglas Crockford speeches, He favours the use of tail recursion over loops. 在道格拉斯·克罗克福德(Douglas Crockford)的演讲中,他赞成使用尾递归而不是循环。 this code was presented, 这段代码被提出了,

function repeat(myFunc) {
  if (myFunc !== undefined) {
    return repeat(myFunc);
  }
}

I thought to define a myFunc but don't know if a static counter can retain its state during function calls or use a global counter. 我曾想定义一个myFunc,但不知道静态计数器是否可以在函数调用期间保留其状态或使用全局计数器。 but being new to javascript I wanted to ask first. 但对于javascript来说,我想先问一下。 How can this be used in an example, say to count down from 10 to 0? 例如,如何将其从10倒数到0? Thanks. 谢谢。

How can this be used in an example, say to count down from 10 to 0? 例如,如何将其从10倒数到0?

Pass a Number to repeat , call repeat with decremented number as parameter until variable parameter is equal to 0 传递Numberrepeat ,以递减的数字作为参数调用repeat ,直到变量参数等于0

 function repeat(n) { console.log(n) if (n) { return repeat(--n); } } repeat(10) 

You need to call the function myFunc somewhere -- and evaluate the result for further call of repeat . 您需要在某个地方调用函数myFunc并评估结果以进一步调用repeat

 function repeat(myFunc) { if (myFunc()) { repeat(myFunc); } } var count = 10; repeat(function () { document.write(count + '<br>'); count--; return count >= 0; }); 

Here is a version that keeps state without global variable: 这是一个保持状态不带全局变量的版本:

 function repeat(myFunc, arg) { if ((arg = myFunc(arg)) !== undefined) { repeat(myFunc, arg); } } repeat(function (count) { document.write(count + ','); count--; if (count >= 0) return count; }, 10); 

Not sure if I understand what approach you want, but you can use this to count down recursively 不知道我是否了解您想要的方法,但是您可以使用它递归递减

function repeat(myFunc, times) {
  if(times > 0 && typeof myFunc == 'function') {
    myFunc(times);
    repeat(myFunc, times-1);
  }
}
repeat(alert, 10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM