Passing a variable Number of arguments in an argument to a javascript function

Can I pass a variable number of arguments to a Javascript function? I have little knowledge in JS. I want to implement something like the following:

function CalculateAB3(data, val1, val2, ...) { ... } 
+7
source share
3 answers

You can pass several parameters in your function and access them through the arguments variable. Below is an example of a function that returns the sum of all the parameters that you passed in it.

 var sum = function () { var res = 0; for (var i = 0; i < arguments.length; i++) { res += parseInt(arguments[i]); } return res; } 

You can call it like this:

 sum(1, 2, 3); // returns 6 
+15
source

The simple answer to your question, of course, you can

But personally, I would like to pass an object, not n number of parameters

Example:

 function CalculateAB3(obj) { var var1= obj.var1 || 0; //if obj.var1 is null, 0 will be set to var1 //rest of parameters } 

Here || is a logical operator for more details visit http://codepb.com/null-coalescing-operator-in-javascript/

A Is there a “null coalescing” operator in JavaScript? is a good read

+3
source

Yes you can do it. Use the arguments variables as here:

 function test() { for(var i=0; i<arguments.length; i++) { console.log(arguments[i]) } } 
0
source

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


All Articles