Javascript unknown number of arguments

in my project, I register various functions (having a different number of arguments) as listeners for a number of events. When an event occurs, I need to run a related function. I get the parameters that need to be passed to the listener method in the form of an array, while the listener function expects every single argument. So, I do it this way, but I don’t like this approach and would like to know if there is an elegant way to do this,

function callListenerWithArgs(func, args){ switch(args.length){ case 1: func(args[0]); break; case 2: func(args[0], args[1]); break; case 3: func(args[0], args[1], args[2]); break; case 4: func(args[0], args[1], args[2], args[3]); break; default: func(); } } 
+6
source share
5 answers

Use .apply

 func.apply(null, args) 

If you need to bind to a specific area, you can pass another argument for use in this inside the function:

 func.apply(scope, args); 

In addition, the nuance of JavaScript is that you can call functions with undefined values. Thus, a small tweak to your existing code will work in 95% of all cases (this is not suggested as a solution, just pointing it out):

 // will handle any number of args up to 7 function callListenerWithArgs(func, args){ func(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } 

If your func is defined as:

 function foo(a, b, c){ } 

you get a , b , c , as well as several undefined values ​​that are ignored. As I said above, this works in 95% of cases. This does not work if you have ever checked arguments.length in the called function, since it will always be the same, regardless of the number of parameters that the function defines.

+2
source

Try using function.apply

 function callListenerWithArgs(func, args){ func.apply(window, args); } 
+1
source

functionName.apply(thisScope, arguments) will be more elegant. The arguments must be an array.

You can build an array like:

 var args = []; switch (arguments.length - 1) { case 0: break; case 1: args.push(arguments[1]); break; case 2: args.push(arguments[1], arguments[2]); break; case 3: args.push(arguments[1], arguments[2], arguments[3]); break; default: args = Array.prototype.slice.call(arguments, 1); } 

or if the array is already built, just pass it as the second argument to .apply

+1
source
 func.apply(this, args); 

See here .

+1
source

You can get the number of function arguments:

 var f = function ( ) { console.log(arguments.length); } f( 2, 3 ) // > 2 

This allows you to implement your func function right on the spot.

 function func() { var nbArgs = arguments.length; // ... } 
-1
source

Source: https://habr.com/ru/post/891129/


All Articles