Is it possible to send a variable number of arguments to a JavaScript function?

后端 未结 12 922
[愿得一人]
[愿得一人] 2020-11-22 10:51

Is it possible to send a variable number of arguments to a JavaScript function, from an array?

var arr = [\'a\',\'b\',\'c\']

var func = function()
{
    //         


        
12条回答
  •  深忆病人
    2020-11-22 11:04

    You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

    To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

    var otherFunc = function() {
       alert(arguments.length); // Outputs: 10
    }
    
    var myFunc = function() {
      alert(arguments.length); // Outputs: 10
      otherFunc.apply(this, arguments);
    }
    myFunc(1,2,3,4,5,6,7,8,9,10);
    

提交回复
热议问题