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

后端 未结 12 745
[愿得一人]
[愿得一人] 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:26

    It's called the splat operator. You can do it in JavaScript using apply:

    var arr = ['a','b','c','d'];
    var func = function() {
        // debug 
        console.log(arguments.length);
        console.log(arguments);
    }
    func('a','b','c','d'); // prints 4 which is what I want, then 'a','b','c','d'
    func(arr); // prints 1, then 'Array'
    func.apply(null, arr); 
    

提交回复
热议问题