Pass unknown number of arguments into javascript function

后端 未结 12 1303
情话喂你
情话喂你 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 10:48

    ES6/ES2015

    Take advantage of the rest parameter syntax.

    function printNames(...names) {
      console.log(`number of arguments: ${names.length}`);
      for (var name of names) {
        console.log(name);
      }
    }
    
    printNames('foo', 'bar', 'baz');
    

    There are three main differences between rest parameters and the arguments object:

    • rest parameters are only the ones that haven't been given a separate name, while the arguments object contains all arguments passed to the function;
    • the arguments object is not a real array, while rest parameters are Array instances, meaning methods like sort, map, forEach or pop can be applied on it directly;
    • the arguments object has additional functionality specific to itself (like the callee property).

提交回复
热议问题