How do I pass a function as a parameter to run multiple times?
I don't understand function closures and anonymous开发者_如何学Go functions very well. What I'm trying to do is create a function that runs the inputted function randomly based on a dice roll:
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();
}
}
What exactly am I doing wrong here? Do I have to store the function in a variable to use it?
By writing foobar()
, you're calling foobar
and passing its return value.
Remove the parentheses to pass the function instead of calling it.
Change:
repeat(1,6,foobar());
to
repeat(1,6,foobar);
精彩评论