Is it possible to get all arguments of a function as single object inside that function?

JavascriptAlgorithmFunctionArgumentsMarshalling

Javascript Problem Overview


In PHP there is func_num_args and func_get_args, is there something similar for JavaScript?

Javascript Solutions


Solution 1 - Javascript

Use arguments. You can access it like an array. Use arguments.length for the number of arguments.

Solution 2 - Javascript

The arguments is an array-like object (not an actual array). Example function...

function testArguments () // <-- notice no arguments specified
{
    console.log(arguments); // outputs the arguments to the console
    var htmlOutput = "";
    for (var i=0; i < arguments.length; i++) {
        htmlOutput += '<li>' + arguments[i] + '</li>';
    }
    document.write('<ul>' + htmlOutput + '</ul>');
}

Try it out...

testArguments("This", "is", "a", "test");  // outputs ["This","is","a","test"]
testArguments(1,2,3,4,5,6,7,8,9);          // outputs [1,2,3,4,5,6,7,8,9]

The full details: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

Solution 3 - Javascript

ES6 allows a construct where a function argument is specified with a "..." notation such as

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}

Solution 4 - Javascript

The arguments object is where the functions arguments are stored.

The arguments object acts and looks like an array, it basically is, it just doesn't have the methods that arrays do, for example:

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

I think the best way to convert a arguments object to a real Array is like so:

argumentsArray = [].slice.apply(arguments);

That will make it an array;

reusable:

function ArgumentsToArray(args) {
    return [].slice.apply(args);
}

(function() {
   args = ArgumentsToArray(arguments);
 
   args.forEach(function(value) {
      console.log('value ===', value);
   });

})('name', 1, {}, 'two', 3)

result: > > value === name
> > value === 1
> > value === Object {}
> > value === two
> > value === 3

Solution 5 - Javascript

You can also convert it to an array if you prefer. If Array generics are available:

var args = Array.slice(arguments)

Otherwise:

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

from Mozilla MDN:

> You should not slice on arguments because it prevents optimizations in > JavaScript engines (V8 for example).

Solution 6 - Javascript

As many other pointed out, arguments contains all the arguments passed to a function.

If you want to call another function with the same args, use apply

Example:

var is_debug = true;
var debug = function() {
  if (is_debug) {
    console.log.apply(console, arguments);
  }
}

debug("message", "another argument")

Solution 7 - Javascript

Similar answer to Gunnar, with more complete example: You can even transparently return the whole thing:

function dumpArguments(...args) {
  for (var i = 0; i < args.length; i++)
    console.log(args[i]);
  return args;
}

dumpArguments("foo", "bar", true, 42, ["yes", "no"], { 'banana': true });

Output:

foo
bar
true
42
["yes","no"]
{"banana":true}

https://codepen.io/fnocke/pen/mmoxOr?editors=0010

Solution 8 - Javascript

In ES6 you can do something like this:

function foo(...args) 
{
   let [a,b,...c] = args;

   console.log(a,b,c);
}


foo(1, null,"x",true, undefined);

Solution 9 - Javascript

Yes if you have no idea that how many arguments are possible at the time of function declaration then you can declare the function with no parameters and can access all variables by arguments array which are passed at the time of function calling.

Solution 10 - Javascript

Hope this helps:

function x(...args) {
    console.log( {...[...args] } ); 
}

x({a:1,b:2}, 'test');

Output:

{ '0': { a: 1, b: 2 }, '1': 'test' }

Solution 11 - Javascript

In ES6, use Array.from:

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionrsk82View Question on Stackoverflow
Solution 1 - JavascriptThomas EdingView Answer on Stackoverflow
Solution 2 - JavascriptLukeView Answer on Stackoverflow
Solution 3 - JavascriptGunnar Forsgren - MobimationView Answer on Stackoverflow
Solution 4 - JavascriptiConnorView Answer on Stackoverflow
Solution 5 - JavascriptIman MohamadiView Answer on Stackoverflow
Solution 6 - JavascriptLasse Skindstad EbertView Answer on Stackoverflow
Solution 7 - JavascriptFrank NockeView Answer on Stackoverflow
Solution 8 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 9 - JavascriptRubi sainiView Answer on Stackoverflow
Solution 10 - JavascriptVonteiView Answer on Stackoverflow
Solution 11 - JavascriptPaul SweatteView Answer on Stackoverflow