Allowing javascript function to accept any number of arguments

后端 未结 6 1780
难免孤独
难免孤独 2020-12-29 05:28

I would like the below function to be more flexible and accept multiple callbacks to other functions if they are defined in the arguments.

$(function() {
            


        
相关标签:
6条回答
  • 2020-12-29 05:59

    Thanks to the spread operator now you can do something like this

    function myFunction(...params) {
      console.log(...params);
    }
    
    myFunction('Many arguments', 1, {two: 3}, ["four", 5]);
    
    // to access one by one
    function oneByOne(...params) {
      params.map(param => {
       console.log(param);   
      });
    }
    
    oneByOne('Many arguments', 1, {two: 3}, ["four", 5]);

    0 讨论(0)
  • 2020-12-29 05:59

    In more recent times you can now make use or the spread and rest operators as detailed here - Pass unknown number of arguments into javascript function

    0 讨论(0)
  • 2020-12-29 06:02

    Use arguments variable.

    function TestMe()
    {
       var args = arguments;
    
       for (var a in args)
       {
         alert(args[a]);
       }
    }
    

    Now you can pass any number of arguments to TestMe function:

    TestMe(1);
    TestMe(1,2,3);
    TestMe(1,2,3,4,5,6);
    TestMe.apply(this, [1,2,3,4,5]); 
    

    etc.

    0 讨论(0)
  • 2020-12-29 06:02

    Yes this is possible, here's an example :

    function myfunct()
    {
    
      var arguments = myfunct.arguments;
    
      for (var i = 0; i < arguments.length; i++)
            {
    
                    alert("Argument " + i + " value = " + arguments[i]);
    
                }
    
    }
    

    You can call this fonction by any number of arguments :

    myfunct("foo");
    
    myfunct("foo","bar");
    
    0 讨论(0)
  • You can use the keyword arguments which is an array of the passed arguments, like this:

    function myFunc() {
       if(arguments.length > 0)     //be sure to check if there are any...
         var arg1 = arguments[0];
    }
    

    However, a much better approach is to accept an object, e.g.:

    function myFunc(settings) {
       settings = settings || {};   //in case it was called as just: myfunc()
       var something = settings.something || "default value";
    }
    

    You'd call it like this:

    myFunc({ something: "value", somethingElse: "otherValue" });
    

    This approach allows you to accept any number of arguments as well, but also have any optional, without a bunch of myFunc(null, null, null, "value") type calls to provide only the parameter you want, plus they're named making this much more maintainable IMO. Here's an edited version of the plugin to demonstrate this.

    0 讨论(0)
  • 2020-12-29 06:15

    Just loop over the arguments object: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/Arguments

    0 讨论(0)
提交回复
热议问题