Pass unknown number of arguments into javascript function

后端 未结 12 1268
情话喂你
情话喂你 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:47

    You can create a function using the spread/rest operator and from there on, you achieved your goal. Please take a look at the chunk below.

    const print_names = (...args) => args.forEach(x => console.log(x));
    
    0 讨论(0)
  • 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).
    0 讨论(0)
  • 2020-12-02 10:48
    function print_args() {
        for(var i=0; i<arguments.length; i++)
            console.log(arguments[i])
    }
    
    0 讨论(0)
  • 2020-12-02 10:48

    let x = function(){
      return [].slice.call(arguments);
    };
    
    console.log(x('a','b','c','d'));

    0 讨论(0)
  • 2020-12-02 10:50

    arguments.length. you can use a for loop on it.

    (function () {
        for (var a = [], i = arguments.length; i--;) {
            a.push(arguments[i]);
        };
        return a;
    })(1, 2, 3, 4, 5, 6, 7, 8)
    
    0 讨论(0)
  • 2020-12-02 10:52
    var 
    print_names = function() {
        console.log.apply( this, arguments );
    };
    
    print_names( 1, 2, 3, 4 );
    
    0 讨论(0)
提交回复
热议问题