简体   繁体   中英

Execute function with array as parameters

I have an array with random count of elements, for example:

var array = [1, 2];

And I want to execute some function with the next parameters:

functionName(SOME_CONST, array[0], array[1])

What is the best way to do this, considering that array could have a different number of parameters?

Have a look at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply for details on how to use the Function.prototype.apply method.

So long as you want to use all of the items in your array as arguments in the function that you are calling, you can use:

function some_method(a, b, c) {}

var array = [1,2];
some_method.apply(this, ['SOME_CONST'].concat(array));

which will result in calling some_method with a being the 'SOME_CONST' and b and c being the first two elements in the array. If you had more elements in the array, they would come next in the arguments list in the some_method function.

You can just call the function and pass in the array itself instead of it's elements like this

function functionName(SOME_CONST, myArray){
  //myArray contains the same elemnts here too
}

then you can call the function like this

   var myArray = [1,2];
   functionName(CONST_VAL,myArray);

The simplest solution would be to pass the whole array to the function and have the function iterate over it. This would allow for a variable length array.

functionName(SOME_CONST, array) {
  for (var ii = 0, len = array.length; ii < len; ii++) {
    // do something.
  }
}

Use .apply , and array join, i mean create new array, let the SOME_CONST be the first element and join the other array which you already have.

You can do like this,

var array = [1, 2];
functionName.apply(thisObj || window, [SOME_CONST].join(array));



function functionName(a, b, c){
 //a is SOME_CONST, b is 1 and c is 2    
}

thisObj is the scope/context of the function which you are calling. If you dont have a thisObj just pass window object

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