JavaScript: How to pass extra parameters to a callback [duplicate]

余生颓废 提交于 2020-02-03 08:54:26

问题


I have a question which has bugged me for a while now.

Let's say I have the following array:

var array = [1, 2, 3]

Now I have a function similar to this:

function print(num, str) {
    console.log(str + ": " + num);
}

Is it possible to call the forEach method and pass a string to it?

// how do I pass "str"?
array.forEach(print);

Thanks!


回答1:


You have two options here:

Either you swap the arguments, so that str comes first. Then you can use function.bind to bind the first arguments of the function:

function print(str, num) {
    console.log(str + ": " + num);
}

array.forEach(print.bind(null, 'someStr'));

Alternatively, you can also create a new (anonymous) function which simply passes some value to the second argument:

array.forEach(function (item) { print(item, 'someStr'); });

With ES6 and the arrow functions, this even gets a bit prettier:

array.forEach(item => print(item, 'someStr'));

Both solutions have a very similar effect in that they create a new function object which is then passed to forEach. What makes more sense to you depends on your use cases.

And just as a note: You just need to remember that the callback passed to forEach actually takes up to three arguments (the item, the item’s index, and the array itself), so be careful when you pass a function that accepts other additional arguments. You can again use a local function to remedy that.




回答2:


Not in this particular situation. The simple solution here is to use an anonymous function wrapper:

array.forEach(function (i) { print(i, str); });

If you reversed the parameters to print, you could do this a little more elegantly like so:

function print(str, num) { .. };

array.forEach(print.bind(null, str));

str will be bound as the first parameter, any parameters that forEach passes when invoking the callback are passed in second, third etc. place.




回答3:


Here you go

var array = [1, 2, 3];

function print(str, num) {
    console.log(str + ": " + num);
}

var str = 'someString';
array.forEach(print.bind(null, str));


来源:https://stackoverflow.com/questions/35406763/javascript-how-to-pass-extra-parameters-to-a-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!