我想使用递归运行某个函数一定次数,例如:repeat(console.log('Hello'), 3)应该打印 Hello 3 次。我试图实现这样的功能,但它只打印一个 word Hello。
function repeat(w, x){
let fun = function(arg){
return arg
}
if (x==1){
return fun(w)
}
else{
return fun(w)+repeat(fun(w), x-1)
}
}
repeat(console.log('Hello'), 3)Run Code Online (Sandbox Code Playgroud)
您没有将函数作为参数传递。您正在调用该函数并传递其返回值。
只通过fun没有参数列表。在初始调用中,您可以使用匿名函数。
function repeat(fun, x) {
if (x == 1) {
return fun()
} else {
return fun() + repeat(fun, x - 1)
}
}
repeat(() => console.log("Hello"), 3);
console.log(repeat((a = 0) => a + 1, 5));Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |