JavaScript:如何将额外的参数传递给回调 [英] JavaScript: How to pass extra parameters to a callback

查看:54
本文介绍了JavaScript:如何将额外的参数传递给回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题困扰了我一段时间.

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

假设我有以下数组:

var array = [1, 2, 3]

现在我有一个类似的功能:

Now I have a function similar to this:

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

是否可以调用forEach方法并将字符串传递给它?

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

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

谢谢!

推荐答案

您在这里有两个选择:

您可以交换参数,以便首先使用str.然后,您可以使用function.bind绑定该函数的第一个参数:

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

有了ES6和箭头功能,它甚至变得更漂亮:

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

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

这两个解决方案都具有非常相似的效果,因为它们创建了一个新的函数对象,然后将其传递给forEach.对您来说更有意义的取决于您的用例.

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.

并请注意:您只需要记住,传递给forEach的回调实际上最多包含三个参数(项目,项目的索引和数组本身),因此在传递函数时要小心接受其他附加参数.您可以再次使用本地函数对此进行补救.

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.

这篇关于JavaScript:如何将额外的参数传递给回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆