[英]I can't seem to get my arguments to pass into a callback
I've created a working recursive for loop, but it only works if my callback has no arguments. 我创建了一个工作递归的for循环,但是只有在我的回调没有参数的情况下它才有效。 I've tried callback(arguments)
and callback(...arguments)
. 我已经尝试过callback(arguments)
和callback(...arguments)
。
Thanks for any help you can provide! 感谢您的任何帮助,您可以提供!
function loopFunc (numOfSteps, callback) { let i = 0; if (i >= numOfSteps) { let i = 0 return } callback() loopFunc(numOfSteps - 1, callback)`enter code here` }
It works if the callback takes no arguments: 如果回调不接受任何参数,它将起作用:
function noArgsHello() { console.log('hello') } const thisWorks = loopFunc(3, noArgsHello); thisWorks()
It doesn't work if the callback takes an argument: 如果回调函数接受一个参数,它将不起作用:
function sayHello (input) { console.log(input) } const thisDoesntWork = loopFunc(3, sayHello('hello'); thisDoesntWork()
You almost there! 你快到了! It depends what is your goal here, you can use either option: 这取决于您的目标是什么,您可以使用以下任何一种方法:
function loopFunc (numOfSteps, callback) {
let i = 0;
if (i >= numOfSteps) {
let i = 0
return
}
callback(numOfSteps)
loopFunc(numOfSteps - 1, callback);
}
function printExtraStuff(greeting) {
return (val) => { console.log('greeting ', val)}
}
function printSteps(num) {
console.log(num);
}
var test1 = function() { loopFunc(3, printExtraStuff('hi there') )};
test1()
var test2 = function() { loopFunc(3, printSteps )};
test2()
In this way: 通过这种方式:
const thisDoesntWork = loopFunc(3, sayHello('hello');
You are not passing a callback anymore, but you are executing the sayHello
function and passing the returned value of that function to the loopFunc
. 您不再传递回调,而是在执行sayHello
函数并将该函数的返回值传递给loopFunc
。
What you can do in these cases, is to use the bind method of functions for passing the function with arguments: 在这些情况下,您可以做的是使用函数的bind方法通过参数传递函数:
const thisDoesntWork = loopFunc(3, sayHello.bind(sayHello, 'hello'));
Or you can pass directly a function which executes your sayHello
so that the argument is still a function and it will be used as callback inside your loopFunc
: 或者,您可以直接传递一个执行sayHello
的函数,以便该参数仍然是一个函数,并将其用作loopFunc
内的loopFunc
:
const thisDoesntWork = loopFunc(3, () => sayHello('hello'));
You need to use an anonymous function if you want to pass parameters in an argument -based function ( callback
is an argument). 如果要在基于参数的函数中传递参数( callback
是一个参数),则需要使用匿名函数。 Your code should instead be like this: 您的代码应改为:
function sayHello(input) { console.log(input) } const works = () => sayHello('hello'); works();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.