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

后端 未结 12 906
[愿得一人]
[愿得一人] 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条回答
  •  萌比男神i
    2020-11-22 11:23

    For those who were redirected here from Passing variable number of arguments from one function to another (which should not be marked as a duplicate of this question):

    If you're trying to pass a variable number of arguments from one function to another, since JavaScript 1.8.5 you can simply call apply() on the second function and pass in the arguments parameter:

    var caller = function()
    {
        callee.apply( null, arguments );
    }
    
    var callee = function()
    {
        alert( arguments.length );
    }
    
    caller( "Hello", "World!", 88 ); // Shows "3".
    

    Note: The first argument is the this parameter to use. Passing null will call the function from the global context, i.e. as a global function instead of the method of some object.

    According to this document, the ECMAScript 5 specification redefined the apply() method to take any "generic array-like object", instead of strictly an Array. Thus, you can directly pass the arguments list into the second function.

    Tested in Chrome 28.0, Safari 6.0.5, and IE 10. Try it out with this JSFiddle.

提交回复
热议问题