Pass unknown number of parameters to JS function

This question already has an answer here:

  • What is the difference between call and apply? 19 answers

  • What you want is probably Function.prototype.apply() .

    Usage:

    var params = [param1, param2, param3];
    functiona.apply(this, params);
    

    As others noted, functiona declaration may use arguments , eg:

    function functiona()
    {
        var param1 = this.arguments[0];
        var param2 = this.arguments[1];
    }
    

    But it can use any number of normal parameters as well:

    function foo(x, y)
    {
        console.log(x);
    }
    foo.apply(this, [10, 0, null]); // outputs 10
    

    Use arguments :

    The arguments object is an Array-like object corresponding to the arguments passed to a function.


    是的,所有传递给JavaScript函数的parameters都可以使用函数中的parameters数组访问。

    function foo () {
        console.log(arguments[0]); // -> bar
        console.log(arguments[1]); // -> baz
    }
    
    foo('bar', 'baz');
    
    链接地址: http://www.djcxy.com/p/18036.html

    上一篇: 请在javascript中解释应用和调用方法

    下一篇: 将未知数量的参数传递给JS函数