In Javascript you can write functions with variable arguments, that is, functions that do not necessarily accept a fixed number of inputs. For example, you can write functions like this:
1 2 3 4 5 6 7 8 9 10 11 12 | / / This function shows the number and value of the arguments / / Passed by reference to the internal arguments and / / Does not require any declaration parametri_variabili function () { 'Numero argomenti passati = ' + arguments. length ) ; alert ('Number of arguments =' + arguments. length); / / Print all the topics '' ; var o =''; var i = 0 ; i < arguments. length ; i ++ ) { for (var i = 0; i <arguments. length; i + +) { i ] + ' \n ' ; or + = arguments [i] + '\ n'; } o ) ; alert (o); } |
So we have:
1 2 3 | // nessuno parametri_variabili () / / none , 32 ) ; // due argomenti: stringa e numero parametri_variabili ("hello", 32); / / two arguments: string and number |
This technique is very useful in many cases, however - in my opinion - you can improve it, as this approach involves:
- The arguments must always follow the same order: arguments [0] is the first, arguments [1] is the second, and so on ...
- The index is for subject access (arguments [0] and arguments [4] for example), then just "read" the entire implementation of the code
An alternative might be to use the inline-objects (Object Literal). For example we could write:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | args ) { parametri_variabili function (args) { args. miaStringa ) ; alert (args. myString); args. mioNumero ) ; alert (args. mioNumero); } / / Using parametri_variabili ({ , myString: 'hello', mioNumero: 32 }); / / Or parametri_variabili ({ , mioNumero: 32, myString: 'hello' }); |
As you can see from the code, the order of arguments, being the property of an object, it is not important. Also in the function code is esssere clearer, treating "property" of an object instead of array indices.
This technique is very good in the case of functions with many arguments, of course.










There are no comments for this post
Leave a comment