In PHP ci sono func_num_args
e func_get_args
, c’è qualcosa di simile per JavaScript?
Usa arguments
. Puoi accedervi come un array. Usa arguments.length
per il numero di argomenti.
Gli argomenti sono oggetti di tipo array (non una matrice reale). Esempio di funzione …
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 += '' + arguments[i] + ' '; } document.write('' + htmlOutput + '
'); }
Provalo…
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]
I dettagli completi: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments
L’object arguments
è dove sono archiviati gli argomenti delle funzioni.
L’argomento object agisce e si presenta come un array, in pratica è, semplicemente non ha i metodi che fanno gli array, ad esempio:
Array.forEach(callback[, thisArg]);
Array.map(callback[, thisArg])
Array.filter(callback[, thisArg]);
Array.slice(begin[, end])
Array.indexOf(searchElement[, fromIndex])
Penso che il modo migliore per convertire un object arguments
in un array reale sia come questo:
argumentsArray = [].slice.apply(arguments);
Questo lo renderà un array;
riutilizzabile:
function ArgumentsToArray(args) { return [].slice.apply(args); } (function() { args = ArgumentsToArray(arguments); args.forEach(function(value) { console.log('value ===', value); }); })('name', 1, {}, 'two', 3)
risultato:
>
value === name
>value === 1
>value === Object {}
>value === two
>value === 3
ES6 consente un costrutto in cui un argomento di funzione è specificato con una notazione “…” come
function testArgs (...args) { // Where you can test picking the first element console.log(args[0]); }
Puoi anche convertirlo in un array se preferisci. Se i generici di array sono disponibili:
var args = Array.slice(arguments)
Altrimenti:
var args = Array.prototype.slice.call(arguments);
da Mozilla MDN :
Non si deve suddividere gli argomenti perché impedisce le ottimizzazioni nei motori JavaScript (ad esempio V8).
Come molti altri hanno sottolineato, gli arguments
contengono tutti gli argomenti passati a una funzione.
Se si desidera chiamare un’altra funzione con gli stessi argomenti, utilizzare apply
Esempio:
var is_debug = true; var debug = function() { if (is_debug) { console.log.apply(console, arguments); } } debug("message", "another argument")
Sì, se non si ha idea del numero di argomenti possibili al momento della dichiarazione della funzione, è ansible dichiarare la funzione senza parametri e accedere a tutte le variabili mediante la matrice di argomenti che vengono passati al momento della chiamata della funzione.
Risposta simile a Gunnar, con un esempio più completo: puoi persino restituire in modo trasparente il tutto:
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 });
Produzione:
foo bar true 42 ["yes","no"] {"banana":true}
In ES6, usa 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"
Per codice non ES6, utilizzare JSON.stringify e 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]
Se è necessaria la conservazione anziché la stringa, utilizzare l’ algoritmo di clonazione strutturata interna .
Se i nodes DOM vengono passati, utilizzare XMLSerializer come in una domanda non correlata .
with (new XMLSerializer()) {serializeToString(document.documentElement) }
Se è in esecuzione come bookmarklet, potrebbe essere necessario racchiudere tutti gli argomenti dei dati strutturati in un costruttore Error per JSON.stringify
affinché funzioni correttamente.
Riferimenti
Struttura Clone CommonJS Module
Clone object JS
MDN: Array.from ()