Pass unknown number of arguments into javascript function

后端 未结 12 1306
情话喂你
情话喂你 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条回答
  •  青春惊慌失措
    2020-12-02 11:03

    You can use the spread/rest operator to collect your parameters into an array and then the length of the array will be the number of parameters you passed:

    function foo(...names) {
        console.log(names);
        return names;
    }
    
    console.log(foo(1, 2, 3, 4).length);
    

    Using BabelJS I converted the function to oldschool JS:

    "use strict";
    
    function foo() {
      for (var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++) {
        names[_key] = arguments[_key];
      }
    
      console.log(names);
      return names;
    }
    

提交回复
热议问题