JavaScript variable number of arguments to function

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

    Another option is to pass in your arguments in a context object.

    function load(context)
    {
        // do whatever with context.name, context.address, etc
    }
    

    and use it like this

    load({name:'Ken',address:'secret',unused:true})
    

    This has the advantage that you can add as many named arguments as you want, and the function can use them (or not) as it sees fit.

提交回复
热议问题