简体   繁体   English

以数组为参数执行函数

[英]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. 请访问https://developer.mozilla.org/zh-CN/JavaScript/Reference/Global_Objects/Function/apply,以获取有关如何使用Function.prototype.apply方法的详细信息。

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. 这将导致调用some_method,其中a为'SOME_CONST',b和c为数组中的前两个元素。 If you had more elements in the array, they would come next in the arguments list in the some_method function. 如果数组中有更多元素,它们将在some_method函数的参数列表中排在第二位。

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. 使用.apply和array join,我的意思是创建新数组,让SOME_CONST作为第一个元素,然后加入另一个已经拥有的数组。

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. thisObj是您正在调用的函数的范围/上下文。 If you dont have a thisObj just pass window object 如果您没有thisObj只需传递window对象

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

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