Czy możliwe jest uzyskanie wszystkich argumentów funkcji jako pojedynczego obiektu wewnątrz tej funkcji?

W PHP jest func_num_args oraz func_get_args, czy jest coś podobnego do JavaScript?

Author: Davіd, 2011-01-08

9 answers

Użycie arguments. Możesz uzyskać do niego dostęp jak do tablicy. Użyj arguments.length dla liczby argumentów.

 316
Author: Thomas Eding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-07 00:05:03

Argumenty to obiekt podobny do tablicy (nie jest rzeczywistą tablicą). Przykładowa funkcja...

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>');
}
Spróbuj...
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]

Pełne szczegóły: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments

 124
Author: Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-07 13:06:03

Obiekt arguments jest miejscem, w którym przechowywane są argumenty funkcji.

Obiekt arguments działa i wygląda jak tablica, w zasadzie jest, po prostu nie ma metod, które robią tablice, na przykład:

Array.forEach(callback[, thisArg]);

Array.map(callback[, thisArg])

Array.filter(callback[, thisArg]);

Array.slice(begin[, end])

Array.indexOf(searchElement[, fromIndex])

Myślę, że najlepszym sposobem na przekonwertowanie arguments obiektu na rzeczywistą tablicę jest tak:

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

To będzie niech będzie tablicą;

Wielokrotnego użytku:

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

(function() {
   args = ArgumentsToArray(arguments);

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

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

Wynik:

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

 20
Author: iConnor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-02 14:09:38

ES6 pozwala na konstruowanie, w którym argument funkcji jest określony przez "..."notacja taka jak

function testArgs (...args) {
 // Where you can test picking the first element
 console.log(args[0]); 
}
 17
Author: Gunnar Forsgren - Mobimation,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-16 14:44:01

Możesz również przekonwertować ją na tablicę, jeśli wolisz. If Array generics are available:

var args = Array.slice(arguments)

Inaczej:

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

From Mozilla MDN :

Nie należy wycinać argumentów, ponieważ zapobiega to optymalizacjom w Silniki JavaScript (na przykład V8).

 9
Author: Iman Mohamadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-21 19:33:28

Jak wiele innych wskazywało, arguments zawiera wszystkie argumenty przekazywane do funkcji.

Jeśli chcesz wywołać inną funkcję z tym samym args, użyj apply

Przykład:

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

debug("message", "another argument")
 6
Author: Lasse Skindstad Ebert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-14 07:27:31

Tak jeśli nie masz pojęcia, ile argumentów jest możliwe w czasie deklaracji funkcji, możesz zadeklarować funkcję bez parametrów i uzyskać dostęp do wszystkich zmiennych za pomocą tablicy argumentów, która jest przekazywana w czasie wywołania funkcji.

 3
Author: Rubi saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-01 19:04:03

Podobna odpowiedź do Gunnara, z pełniejszym przykładem: Można nawet przejrzyście zwrócić całość:

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 });

Wyjście:

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

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

 3
Author: Frank Nocke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 11:23:46

W ES6 użyj 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"

Dla kodu innego niż ES6, użyj JSON.stringify i 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]

Jeśli konieczne jest zachowanie zamiast stringifikacji, użyj wewnętrznego strukturalnego algorytmu klonowania .

Jeśli węzły DOM są przekazywane, użyj XMLSerializer jak w niepowiązanym pytaniu.

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

Jeśli działa jako bookmarklet, może być konieczne zawinięcie każdego argumentu danych strukturalnych w konstruktor błędu, aby JSON.stringify zadziałało jak należy.

Referencje

 -11
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:33