JavaScript variable number of arguments to function

后端 未结 11 658
太阳男子
太阳男子 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:30

    While @roufamatic did show use of the arguments keyword and @Ken showed a great example of an object for usage I feel neither truly addressed what is going on in this instance and may confuse future readers or instill a bad practice as not explicitly stating a function/method is intended to take a variable amount of arguments/parameters.

    function varyArg () {
        return arguments[0] + arguments[1];
    }
    

    When another developer is looking through your code is it very easy to assume this function does not take parameters. Especially if that developer is not privy to the arguments keyword. Because of this it is a good idea to follow a style guideline and be consistent. I will be using Google's for all examples.

    Let's explicitly state the same function has variable parameters:

    function varyArg (var_args) {
        return arguments[0] + arguments[1];
    }
    

    Object parameter VS var_args

    There may be times when an object is needed as it is the only approved and considered best practice method of an data map. Associative arrays are frowned upon and discouraged.

    SIDENOTE: The arguments keyword actually returns back an object using numbers as the key. The prototypal inheritance is also the object family. See end of answer for proper array usage in JS

    In this case we can explicitly state this also. Note: this naming convention is not provided by Google but is an example of explicit declaration of a param's type. This is important if you are looking to create a more strict typed pattern in your code.

    function varyArg (args_obj) {
        return args_obj.name+" "+args_obj.weight;
    }
    varyArg({name: "Brian", weight: 150});
    

    Which one to choose?

    This depends on your function's and program's needs. If for instance you are simply looking to return a value base on an iterative process across all arguments passed then most certainly stick with the arguments keyword. If you need definition to your arguments and mapping of the data then the object method is the way to go. Let's look at two examples and then we're done!

    Arguments usage

    function sumOfAll (var_args) {
        return arguments.reduce(function(a, b) {
            return a + b;
        }, 0);
    }
    sumOfAll(1,2,3); // returns 6
    

    Object usage

    function myObjArgs(args_obj) {
        // MAKE SURE ARGUMENT IS AN OBJECT OR ELSE RETURN
        if (typeof args_obj !== "object") {
            return "Arguments passed must be in object form!";
        }
    
        return "Hello "+args_obj.name+" I see you're "+args_obj.age+" years old.";
    }
    myObjArgs({name: "Brian", age: 31}); // returns 'Hello Brian I see you're 31 years old
    

    Accessing an array instead of an object ("...args" The rest parameter)

    As mentioned up top of the answer the arguments keyword actually returns an object. Because of this any method you want to use for an array will have to be called. An example of this:

    Array.prototype.map.call(arguments, function (val, idx, arr) {});
    

    To avoid this use the rest parameter:

    function varyArgArr (...var_args) {
        return var_args.sort();
    }
    varyArgArr(5,1,3); // returns 1, 3, 5
    
    0 讨论(0)
  • 2020-11-22 02:32

    It is preferable to use rest parameter syntax as Ramast pointed out.

    function (a, b, ...args) {}
    

    I just want to add some nice property of the ...args argument

    1. It is an array, and not an object like arguments. This allows you to apply functions like map or sort directly.
    2. It does not include all parameters but only the one passed from it on. E.g. function (a, b, ...args) in this case args contains argument 3 to arguments.length
    0 讨论(0)
  • 2020-11-22 02:37

    Yes, just like this :

    function load()
    {
      var var0 = arguments[0];
      var var1 = arguments[1];
    }
    
    load(1,2);
    
    0 讨论(0)
  • 2020-11-22 02:52

    Sure, just use the arguments object.

    function foo() {
      for (var i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);
      }
    }
    
    0 讨论(0)
  • 2020-11-22 02:52

    Be aware that passing an Object with named properties as Ken suggested adds the cost of allocating and releasing the temporary object to every call. Passing normal arguments by value or reference will generally be the most efficient. For many applications though the performance is not critical but for some it can be.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题