gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:24:53 25 4
gpt4 key购买 nike

我不是很了解函数闭包和匿名函数。我想做的是创建一个函数,该函数根据掷骰子随机运行输入的函数:

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

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

最佳答案

通过编写 foobar(),您正在调用 foobar 并传递其返回值。

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

关于javascript - 如何将函数作为参数传递以运行多次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6193654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com