简体   繁体   English

在JavaScript / jQuery中多次调用带有参数的函数的简写?

[英]Shorthand for calling a function with an argument more than once in JavaScript/jQuery?

I have a function with an argument, eg: 我有一个带参数的函数,例如:

function doThisThing(toThis){
    // some function
}

So far I've been calling the function multiple times with different arguments like this: 到目前为止,我一直用不同的参数多次调用该函数,如下所示:

doThisThing ( bananas );
doThisThing ( apples );
doThisThing ( pears );

Is there a way of doing this more succinctly? 有没有办法更简洁地做到这一点? I've tried things like doThisThing ( bananas, apples, pears ); 我尝试过像doThisThing ( bananas, apples, pears ); and so on, but to no avail... 等等,但无济于事......

[bananas, apples, pears].forEach(doThisThing);

如果您可以依赖Array.prototype.forEach支持,则doThisThing只接受一个参数。

I don't really see the point but 我真的没有看到这一点,但是

[bananas, apples, pears].forEach(doThisThing);

Code being concise is a good thing, but it's also important for it to not be weird. 简洁的代码是一件好事,但同样重要的是它并不奇怪。

Now, if doThisThing(banana) etc are things you do a lot , then you can create pre-arranged shortcuts: 现在,如果doThisThing(banana)等是您做了很多事情,那么您可以创建预先安排的快捷方式:

var doBanana = doThisThing.bind(undefined, banana); // etc

Then doBanana() is equivalent to doThisThing(banana); 然后doBanana()相当于doThisThing(banana); . This can be handy when you've got functions that take more than one argument, and which are designed such that the first argument has few variations but the second argument has many. 当你拥有多个参数的函数时,这可以很方便,并且这些函数的设计使得第一个参数的变化很少,但第二个参数有很多变量。 You can create a bound version with a pre-supplied value for the first argument, and then the argument(s) passed in to that will succeed the "fixed" pre-arranged value. 您可以使用第一个参数的预先提供的值创建绑定版本,然后传入其中的参数将成为“固定”预先安排的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM