Passing Unknown Number of Arguments in a Function

Pass unknown number of arguments into JavaScript function

ES3 (or ES5 or oldschool JavaScript)

You can access the arguments passed to any JavaScript function via the magic arguments object, which behaves similarly to an array. Using arguments your function would look like:

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

It's important to note that arguments is not an array. MDC has some good documentation on it: https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#Using_the_arguments_object

If you want to turn arguments into an array so that you can do things like .slice(), .push() etc, use something like this:

var args = Array.prototype.slice.call(arguments);

ES6 / Typescript

There's a better way! The new rest parameters feature has your back:

var print_names = function(...names) {
for (let i=0; i<names.length; i++) console.log(names[i]);
}

JavaScript: Pass unknown number of arguments from one method to another

You can use rest syntax to collect all the arguments into an array in acceptArguments (which is preferred over using the arguments variable), and then spread those arguments into the call of secondFunction:

function acceptArguments(...args) {

secondFunction(...args);

}

function secondFunction(v1, v2, v3, v4) {

console.log(v1, v2, v3, v4);

}

acceptArguments(1, 2, 3, 4)

Calling a function with unknown number of parameters Python

You could try something like this:

string_input = "IF service IS poor OR food IS rancid THEN tip IS cheap"
string_input = string_input.replace(" THEN ", '"], ').replace(' IS ', '["').strip("IF ").replace(" OR ", '"] | ') +'"]'
eval('ctrl.Rule({})'.format(string_input))

But be warned you need to be very very careful with eval. It is a security risk because user can execute code this way!!! Before using this you might to do research on how to prevent this security issue.

Unknown number of arguments in function

Variable argument lists have several drawbacks:

  • Callers can pass in everything they want.
  • If a non-POD object is passed, undefined behaviour is summoned
  • You can't rely on the number of arguments (the caller can make errors)
  • You put a LOT of responsibility on your CLIENT, for whom you intended to have an easier time with your library code (practical example: format-string-bugs/-errors)

Compared to variadic templates:

  • Compile time list size is known
  • Types are known at compile time
  • You have the responsibility for stuff, not your client, which is like it should be.

Example:

void pass_me_floats_impl (std::initializer_list<float> floats) {
...
}

You can put this into the private section of a class declaration or in some detail namespace. Note: pass_me_floats_impl() doesn't have to be implemented in a header.

Then here's the nice stuff for your client:

template <typename ...ArgsT>
void pass_me_floats (ArgsT ...floats) {
pass_me_floats_impl ({floats...});
}

He now can do:

pass_me_floats ();
pass_me_floats (3.5f);
pass_me_floats (1f, 2f, 4f);

But he can't do:

pass_me_floats (4UL, std::string());

because that would emit a compile error inside your pass_me_floats-function.

If you need at least, say, 2 arguments, then make it so:

template <typename ...ArgsT>
void pass_me_floats (float one, float two, ArgsT... rest) {}

And of course, if you want it a complete inline function, you can also

template <typename ...ArgsT>
void pass_me_floats (ArgsT... rest) {
std::array<float, sizeof...(ArgsT)> const floaties {rest...};

for (const auto f : floaties) {}
}

passing unknown number of arguments in a function

Swift Variadic Parameters accepts zero or more parameters of a specified type. Syntax of variadic parameters is, insert three period characters (...) after the parameter’s type name.

func anyNumberOfTextField(_ textField: UITextField...) {

}

Now you can pass any number of textField.

anyNumberField(UITextField(),UITextField(), UITextField(), UITextField())

Note: A function may have at most one variadic parameter.

For more info check this Swift Functions

There is another way you can do that is called Array Parameter. There are some pros and cons of these two methods. You will find the difference here link.

Function with unknown number of parameters in C

Yes you can do it in C using what are referred to as Variadic Functions.
The standard printf() and scanf() functions do this, for example.

Put the ellipsis (three dots) as the last parameter where you want the 'variable number of parameters to be.

To access the parameters include the <stdarg.h> header:

#include <stdarg.h>

And then you have a special type va_list which gives you the list of arguments passed, and you can use the va_start, va_arg and va_end macros to iterate through the list of arguments.

For example:

#include <stdarg.h>

int myfunc(int count, ...)
{
va_list list;
int j = 0;

va_start(list, count);
for(j=0; j<count; j++)
{
printf("%d", va_arg(list, int));
}

va_end(list);

return count;
}

Example call:

myfunc(4, -9, 12, 43, 217);

A full example can be found at Wikipedia.

The count parameter in the example tells the called function how many arguments are passed. The printf() and scanf() find that out via the format string, but a simple count argument can do it too. Sometimes, code uses a sentinel value, such as a negative integer or a null pointer (see
execl()
for example).

Can a variable number of arguments be passed to a function?

Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg

>>> manyArgs(1)
I was called with 1 arguments: (1,)
>>> manyArgs(1, 2, 3)
I was called with 3 arguments: (1, 2, 3)

As you can see, Python will unpack the arguments as a single tuple with all the arguments.

For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

Pass unknown number of parameters to JS function

What you want is probably Function.prototype.apply().

Usage:

var params = [param1, param2, param3];
functiona.apply(this, params);

As others noted, functiona declaration may use arguments, e.g.:

function functiona()
{
var param1 = this.arguments[0];
var param2 = this.arguments[1];
}

But it can use any number of normal parameters as well:

function foo(x, y)
{
console.log(x);
}
foo.apply(this, [10, 0, null]); // outputs 10

How to create a function with an unknown number of parameters?

You can use fold expressions for this:

template<typename ...Ts>
double calculate_average(Ts... ts)
{
return (((double)ts / sizeof...(ts)) + ... + 0);
}

Note the sizeof...(ts), is a separate primitive for parameter packs. It's not a pack expansion, but instead gives the number of arguments that are passed into the function.

Here's a demo.



Related Topics



Leave a reply



Submit