简体   繁体   中英

How to call a function when we have its arguments in an array

Let's say we have a function

f = function(a, b, c){
    // do something important
}

and an array containing the arguments

var args = [5, 'string', 12] // just any values

Obviously, I could call my function like this :

f(args[0], args[1], args[2])

This is really not elegant, and I look for a better way to accomplish this. Thanks for your suggestions.

您正在寻找Function.apply()

f.apply(window, args); // pass something other than null to set 'this' within the call

Use .apply() .

f.apply(window, args);

This will work with any array-like object in the second argument position.

It invokes the function f , and sets the first argument you pass as its this value (here I just used window ) , and distributes the members of the second argument as individual arguments to the function.

The result is as though you had done this:

f(5, 'string', 12);

There's a counterpart to the Function.prototype.apply method called .call() . The .call() method is exactly the same, except that you pass the arguments individually.

f.call(window, 5, 'string, 12);

The purpose of this is the call the function like normal, but set the this value manually.

Use .apply() . The second argument lets you specify an array of arguments to the function you are trying to call. The first argument is the value of this you want in the context of the function.

So in your case it would be:

f.apply(null, args);

or

f.apply(window, args);

If you want this within the context of f to be the window object.

It depends of your needs (of course)

if elements are homogenous

var sum = function(numbers) {
   // do some calculations
}

var randomees = [5, 6, 12]
var total = sum(randomees);

If they are not, they should have some kind of description. Ie if you are defining options or parameters, then you would consider this

var parameters = {
    size:13,
    shipped:true,
    description:"Laptop"
}

var displayLaptop = function(characteristics) {
    console.log(characteristics.size)
}

(or even play with some jQuery.extend ish method)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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