JavaScript variable number of arguments to function

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

    Although I generally agree that the named arguments approach is useful and flexible (unless you care about the order, in which case arguments is easiest), I do have concerns about the cost of the mbeasley approach (using defaults and extends). This is an extreme amount of cost to take for pulling default values. First, the defaults are defined inside the function, so they are repopulated on every call. Second, you can easily read out the named values and set the defaults at the same time using ||. There is no need to create and merge yet another new object to get this information.

    function load(context) {
       var parameter1 = context.parameter1 || defaultValue1,
           parameter2 = context.parameter2 || defaultValue2;
    
       // do stuff
    }
    

    This is roughly the same amount of code (maybe slightly more), but should be a fraction of the runtime cost.

提交回复
热议问题