JavaScript arguments to implement variable-length parameters.
In C #, there are variable long parameter params[], but in JS, how to implement this variable parameter?
Variable-length parameters
Arguments is a very good solution and has never known that JavaScript has this thing.
First take a look at the application scene, using arguments to pass any number of parameters to the JS function in the writing.
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's 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, and using the call method may use the shift function of the array on it, but try not to try to change the arguments. can easily cause confusion.
If you do, you can copy the contents of the arguments to a new array and modify them on the new array.
var args = [].slice.call(arguments);
Binding arguments with variables to achieve cross function access
The arguments variable is implicitly bound to the body of each function, and the note is within each function.
An example of an iterator can illustrate this 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 way, in the inner layer can be accessed, 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 save 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
The above is the entire content of this article, I hope to help you, thank you for the support of cloud habitat community!