JavaScript variable number of arguments to function

后端 未结 11 665
太阳男子
太阳男子 2020-11-22 02:14

Is there a way to allow \"unlimited\" vars for a function in JavaScript?

Example:

load(var1, var2, var3, var4, var5, etc...)
load(var1)
11条回答
  •  别那么骄傲
    2020-11-22 02:53

    In (most) recent browsers, you can accept variable number of arguments with this syntax:

    function my_log(...args) {
         // args is an Array
         console.log(args);
         // You can pass this array as parameters to another function
         console.log(...args);
    }
    

    Here's a small example:

    function foo(x, ...args) {
      console.log(x, args, ...args, arguments);
    }
    
    foo('a', 'b', 'c', z='d')
    
    =>
    
    a
    Array(3) [ "b", "c", "d" ]
    b c d
    Arguments
    ​    0: "a"
        ​1: "b"
        ​2: "c"
        ​3: "d"
        ​length: 4
    

    Documentation and more examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

提交回复
热议问题