JavaScript variable number of arguments to function

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

    As mentioned already, you can use the arguments object to retrieve a variable number of function parameters.

    If you want to call another function with the same arguments, use apply. You can even add or remove arguments by converting arguments to an array. For example, this function inserts some text before logging to console:

    log() {
        let args = Array.prototype.slice.call(arguments);
        args = ['MyObjectName', this.id_].concat(args);
        console.log.apply(console, args);
    }
    

提交回复
热议问题