Function with variable amount of parameters, what better way to do?

Asked

Viewed 666 times

6

I would like to do a function without defining the amount of parameters needed. What ways or alternatives can I use to get this result?

3 answers

11


You can use . call() or . aplly or even call the function in the most convectional way, and within the function, use the reserved word arguments

function foo() {
    console.log(this, arguments);
}
foo.call('foo', 1, {animal: 'cão'}, 3)
foo.apply('foo', [1, {animal: 'cão'}, 3])
foo('foo', 1, {animal: 'cão'}, 3, 4);

http://jsfiddle.net/NDZeV/

These 3 different ways of calling a function and passing arguments give the same result in the first two cases.

'foo', // usando o call() e o apply() o primeiro argumento é o this
Arguments[3] // aqui o arguments têm em forma tipo array os restantes argumentos
    0: 1                // o mesmo que arguments[0], ou seja 1
    1: {animal: 'cão'}  // o mesmo que arguments[1], ou seja {animal: 'cão'} 
    2: 3                // o mesmo que arguments[2], ou seja 3

In the case of the last example, calling the function directly the this is related to the scope in which it is probably window and it has nothing to do with the parameters passed to the function. In this case the àrgumentstem somente valores passados da forma mais comum ou sejafunc(a, b, c)`. In this above code example this gives:

window, // aqui o "this" nõ tem a ver com os parametros da função e vai buscar o valor do this no escopo em que a função estiver
Arguments[3] // argumentos
    0: 'foo'            // o mesmo que arguments[0], ou seja 'foo'
    1:                  // o mesmo que arguments[1], ou seja 1
    2: {animal: 'cão'}  // o mesmo que arguments[2], ou seja {animal: 'cão'} 
    3: 4                // o mesmo que arguments[3], ou seja 3
    4: 4                // o mesmo que arguments[4], ou seja 4

This object arguments is a local variable of the function and is not an array but rather as @bfavaretto indicated is a array-like Object, and share property for example length arrays.

MDN:

  • If I call the function foo(number), where int number = 10; How to give an Alert of this variable within the function?

  • Thanks @bfavaretto. Just one more question. If I want to give an Alert that shows the variable name, how would it look?

  • @Joaopaulo as so, which means "the variable name"?

  • @bfavaretto you’re absolutely right. I’ll correct...

  • If I call foo(number, letter) and want to show on the screen the string "number" and "letter", that is, the name of the variables I passed as parameter.

  • @Joaopaulo, to have names you must use objects, there you must use Object.keys(numero);, if you want to know what type of variable is you have to use typeof. You can better specify which one you’re looking for?

  • My ultimate goal is to make a function that creates a string by mounting a Json object. when I called foo(number, letter); that would be: "{ 'numero': '1', 'letter' :'A' }"; therefore, I would like to extract the name of the variable.

  • @Joaopaulo You can’t extract the names from the function’s parameters. I mean, you can, but it’s quite a gambiarra. Now, what you wanted was not just to pass any number of parameters? In this case you would not use named parameters, right?

  • 1

    I use named parameters. It has ajax in every application and I always have to create the data string with the parameters and values to send to Controller C#. Ai would like to set up this function to simplify.

Show 4 more comments

8

Sergio’s answer is excellent and I agree it’s the right one. I will leave an alternative only to increase the range of options for those who want to work with multiple parameters.

There is a technique that is to receive a single parameter - a dictionary of options. This technique is used in frameworks like the jQuery, for example.

An example:

function AplicaCSS (options) {
    if (!options) return;
    var font = options.font || "arial 12";
    var height = options.height || "15px";
    var width = options.width || "100px";
    /*etc., etc.*/
}

Note that in this way, you simply pass an object whose properties may vary. If I call the function that way:

AplicaCSS({font: "comic sans bold"});

... It works. The way the function is, the "missing" properties are set to default values. If I call the function as follows:

AplicaCSS({height: "10px", width: "50px"});

... Or:

AplicaCSS({});

... Or even:

AplicaCSS({bar: "lolwut"}); // Como é uma propriedade que não espero, 'bar' é ignorada.

... It works the same way. So the amount of variable parameters is the object you pass, not the function itself. This gives you a lot of flexibility, plus you have a function with fixed signature and known. It is also worth documenting the properties that you look for in the received object, for who will use its function ;)

1

you can use an array for the parameters or it is not necessary to define them.

creates a rule to dynamically handle these values and solved your problem.

I use it a lot

  • 6

    Could you add an example to your answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.