Pass unknown number of arguments into javascript function

后端 未结 12 1307
情话喂你
情话喂你 2020-12-02 10:17

Is there a way to pass an unknown number of arguments like:

var print_names = function(names) {
    foreach(name in names) console.log(name); // something li         


        
12条回答
  •  旧时难觅i
    2020-12-02 10:58

    There is a hidden object passed to every function in JavaScript called arguments.

    You would just use arguments.length to get the amount of arguments passed to the function.

    To iterate through the arguments, you would use a loop:

    for(var i = arguments.length; i--) {
       var arg = arguments[i];
    }
    

    Note that arguments isn't a real array, so if you needed it as an array you would convert it like this:

    var args = Array.prototype.slice.call(arguments);
    

提交回复
热议问题