JavaScript variable number of arguments to functio

2018-12-31 05:43发布

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

Example:

load(var1, var2, var3, var4, var5, etc...)
load(var1)

11条回答
笑指拈花
2楼-- · 2018-12-31 06:21

Sure, just use the arguments object.

function foo() {
  for (var i = 0; i < arguments.length; i++) {
    console.log(arguments[i]);
  }
}
查看更多
其实,你不懂
3楼-- · 2018-12-31 06:26

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
查看更多
牵手、夕阳
4楼-- · 2018-12-31 06:29

Use the arguments object when inside the function to have access to all arguments passed in.

查看更多
长期被迫恋爱
5楼-- · 2018-12-31 06:35

I agree with Ken's answer as being the most dynamic and I like to take it a step further. If it's a function that you call multiple times with different arguments - I use Ken's design but then add default values:

function load(context) {

    var defaults = {
        parameter1: defaultValue1,
        parameter2: defaultValue2,
        ...
    };

    var context = extend(defaults, context);

    // do stuff
}

This way, if you have many parameters but don't necessarily need to set them with each call to the function, you can simply specify the non-defaults. For the extend method, you can use jQuery's extend method ($.extend()), craft your own or use the following:

function extend() {
    for (var i = 1; i < arguments.length; i++)
        for (var key in arguments[i])
            if (arguments[i].hasOwnProperty(key))
                arguments[0][key] = arguments[i][key];
    return arguments[0];
}

This will merge the context object with the defaults and fill in any undefined values in your object with the defaults.

查看更多
余生请多指教
6楼-- · 2018-12-31 06:35

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.

查看更多
临风纵饮
7楼-- · 2018-12-31 06:36

Yes, just like this :

function load()
{
  var var0 = arguments[0];
  var var1 = arguments[1];
}

load(1,2);
查看更多
登录 后发表回答