-1

please help me with the following problem: The function arguments and the number of them may differ each time. How to properly read the arguments ?

For example:

    
function fnMyfunction (params)
{ console.log (params) } //--> displays 1

var res = fnMyfunction ("1", 2, 78, "s");

When I read the params inside the function I get only the first value. Is it possible to send arguments as a list ?

Luqpa
  • 47
  • 1
  • 2
  • read the documentation on the `arguments` in JS. – Hrishi Oct 10 '14 at 08:05
  • @Luqpa It has been answered here http://stackoverflow.com/questions/15210312/looping-through-unknown-number-of-array-arguments – mjroodt Oct 10 '14 at 08:11
  • Thanks - arguments builtin word was what i needed .... Finally I got this: var args = Array.prototype.slice.call(arguments); – Luqpa Oct 10 '14 at 09:43

2 Answers2

0

Use arguments inside the function:

function fnMyfunction ()
{ console.log (arguments); }

var res = fnMyfunction ("1", 2, 78, "s");
artm
  • 8,554
  • 3
  • 26
  • 43
0

You basically have two options. The first one is to use arguments array-like collection to access all passed parameter.

function fnMyfunction(params) {
    console.log(arguments);
} //--> ["1", 2, 78, "s"] array-like collection, while params is "1"

var res = fnMyfunction("1", 2, 78, "s");

Another option could be to pass arguments already in for of array or object:

function fnMyfunction(params) {
    console.log (params);
} //--> ["1", 2, 78, "s"] is array

var res = fnMyfunction(["1", 2, 78, "s"]);

In general if you plan to use function with many arguments it often makes sense to design it so it accepts only fewer parameters, usually just one object with the set of necessary properties. This is the most flexible approach to the problem.

dfsq
  • 191,768
  • 25
  • 236
  • 258