In C #, there are variable length parameters params[], but in JS, how to implement this variable parameter?
one, variable length parameters
Arguments is a very good solution and has never known JavaScript to have this thing.
Let's take a look at the application scenario and use arguments to pass in any number of arguments into the JS function.
function Test () { console.log (arguments[0]); Console.log (Arguments[1]); Console.log (arguments[2]); }; Test (1, 2, 3);
Output 1 2 3;
Of course, you can also put an array in a JavaScript function, but it is fixed-length.
second, do not directly modify the arguments object
The arguments object is similar to an array, but in fact it is not an array, using the call method, you might use the shift function of the array for it, but try not to change the arguments. It is easy to cause confusion.
If you really want to modify it, you can copy the contents of the arguments to a new array and modify it on the new array.
var args = [].slice.call (arguments);
third, using variable binding arguments to achieve cross function access
Arguments variables are implicitly bound to each function body, note that each function is inside.
An example of an iterator can illustrate the problem;
function values () { //values has its own arguments var i = 0, n = arguments.length; return { hasnext:function () { return i < n; Hasnext has its own arguments }, next:function () { if (i >= N) { throw new Error ("Already the last element!"); } return arguments[i++]; Next has its own arguments } } } var it = values (1, 2, 3, 4, 5, 6, 7); Console.log (It.next ()); Undefined console.log (It.next ()); Undefined console.log (It.next ()); Undefined
If you want to access the outer function of the arguments, then only through the local variable binding, can be accessed in the inner layer, the above example can be transformed into
function values () { //values has its own arguments var i = 0, n = arguments.length, Ourterargs = arguments; return { hasnext:function () { return i < n; Hasnext has its own arguments }, next:function () { if (i >= N) { throw new Error ("Already the last element!"); } return ourterargs[i++]; Ourterargs outer Arguments}} } var it = values (1, 2, 3, 4, 5, 6, 7); Console.log (It.next ()); 1 console.log (It.next ()); 2 Console.log (It.next ()); 3
JavaScript arguments explains that variable-length parameters are implemented.