JavaScript variable number of arguments to function

后端 未结 11 666
太阳男子
太阳男子 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条回答
  •  梦毁少年i
    2020-11-22 02:53

    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.

提交回复
热议问题