如何将函数作为参数传递多次运行?

Das*_*aru 2 javascript parameters function

我不太了解函数闭包和匿名函数.我要做的是创建一个函数,根据骰子卷随机运行输入的函数:

repeat(1,6,foobar());

function repeat(numDie, dieType, func){
    var total = 0;
    for (var i=0; i < numDie; i++){
        var dieRoll = Math.floor(Math.random()*dieType)+1;
        total += dieRoll;
    }
    for (var x=0; x < total; x++){
        func();
    }
}
Run Code Online (Sandbox Code Playgroud)

我到底错在了什么?我是否必须将函数存储在变量中才能使用它?

SLa*_*aks 8

通过写作foobar(),您将调用 foobar并传递其返回值.

删除括号以传递函数而不是调用它.


Cha*_*ndu 6

更改:

重复(1,6,foobar的());

repeat(1,6,foobar); 
Run Code Online (Sandbox Code Playgroud)