Javascript 尾递归而不是循环

Javascript tail recursion instead of loop

在 Douglas Crockford 的一次演讲中,他赞成使用尾递归而不是循环。此代码已提交,

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

我想定义一个 myFunc 但不知道静态计数器是否可以在函数调用期间保持其状态或使用全局计数器。但作为 javascript 的新手,我想先问一下。如何在示例中使用它,比如从 10 倒数到 0?谢谢

不确定我是否理解你想要的方法,但你可以使用它递归倒计时

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

How can this be used in an example, say to count down from 10 to 0?

传递一个Numberrepeat,调用repeat以递减数字作为参数直到变量参数等于0

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

repeat(10)

您需要在某处调用函数 myFunc -- 并评估结果以进一步调用 repeat

function repeat(myFunc) {
    if (myFunc()) {
        repeat(myFunc);
    }
}

var count = 10;

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

这是一个没有全局变量的保持状态的版本:

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);