Is it possible to send a variable number of arguments to a JavaScript function?

后端 未结 12 738
[愿得一人]
[愿得一人] 2020-11-22 10:51

Is it possible to send a variable number of arguments to a JavaScript function, from an array?

var arr = [\'a\',\'b\',\'c\']

var func = function()
{
    //         


        
相关标签:
12条回答
  • 2020-11-22 11:03

    Yes you can pass variable no. of arguments to a function. You can use apply to achieve this.

    E.g.:

    var arr = ["Hi","How","are","you"];
    
    function applyTest(){
        var arg = arguments.length;
        console.log(arg);
    }
    
    applyTest.apply(null,arr);
    
    0 讨论(0)
  • 2020-11-22 11:04

    You can actually pass as many values as you want to any javascript function. The explicitly named parameters will get the first few values, but ALL parameters will be stored in the arguments array.

    To pass the arguments array in "unpacked" form, you can use apply, like so (c.f. Functional Javascript):

    var otherFunc = function() {
       alert(arguments.length); // Outputs: 10
    }
    
    var myFunc = function() {
      alert(arguments.length); // Outputs: 10
      otherFunc.apply(this, arguments);
    }
    myFunc(1,2,3,4,5,6,7,8,9,10);
    
    0 讨论(0)
  • 2020-11-22 11:07

    The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:

    var arr = ['quick', 'brown', 'lazy'];
    
    var sprintf = function(str, ...args)
    {
        for (arg of args) {
            str = str.replace(/%s/, arg);
        }
        return str;
    }
    
    sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
    sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
    

    Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr); is not yet supported. You can find an ES6 compatibility table here.

    Note also the use of for...of, another ES6 addition. Using for...in for arrays is a bad idea.

    0 讨论(0)
  • 2020-11-22 11:07

    This is a sample program for calculating sum of integers for variable arguments and array on integers. Hope this helps.

    var CalculateSum = function(){
        calculateSumService.apply( null, arguments );
    }
    
    var calculateSumService = function(){
        var sum = 0;
    
        if( arguments.length === 1){
            var args = arguments[0];
    
            for(var i = 0;i<args.length; i++){
               sum += args[i]; 
            }
        }else{
            for(var i = 0;i<arguments.length; i++){
               sum += arguments[i]; 
            }        
        }
    
         alert(sum);
    
    }
    
    
    //Sample method call
    
    // CalculateSum(10,20,30);         
    
    // CalculateSum([10,20,30,40,50]);
    
    // CalculateSum(10,20);
    
    0 讨论(0)
  • 2020-11-22 11:10

    With ES6 you can use rest parameters for varagrs. This takes the argument list and converts it to an array.

    function logArgs(...args) {
        console.log(args.length)
        for(let arg of args) {
            console.log(arg)
        }
    }
    
    0 讨论(0)
  • Do you want your function to react to an array argument or variable arguments? If the latter, try:

    var func = function(...rest) {
      alert(rest.length);
    
      // In JS, don't use for..in with arrays
      // use for..of that consumes array's pre-defined iterator
      // or a more functional approach
      rest.forEach((v) => console.log(v));
    };
    

    But if you wish to handle an array argument

    var fn = function(arr) {
      alert(arr.length);
    
      for(var i of arr) {
        console.log(i);
      }
    };
    
    0 讨论(0)
提交回复
热议问题