Because of the error in language design, arguments can be treated as an array.
Copy Code code as follows:
function zero () {
Console.log (Arguments[0]);
}
There will also be
Copy Code code as follows:
function zero () {
for (Var i=0;i<arguments.length;i++) {
Console.log (Arguments[i]);
}
}
It leverages the fact that JavaScript is JAVASC
The arguments variable here provides an array-like interface to the argument. Because of the variable parameters of the arguments here, we can use this interesting thing to do some interesting things, such as overloading.
Javscript overload
There's a question about overloading on the stackvoerflow, so there's the first answer.
Copy Code code as follows:
if (typeof friend = = "undefined") {
} else {
}
And then there's one answer.
Copy Code code as follows:
Switch (arguments.length) {
Case 0:
Probably Error
Break
Case 1:
Do something
Break
Case 2:
Default://fall through to handle case of the more parameters
Do something else
Break
}
Just this way is really not good to see, is our function finally to become such a child?
Copy Code code as follows:
function Zero1 () {
Console.log (' arguments 1 ')
};
function Zero2 () {
Console.log (' Arguments 2 ')
};
function zero () {
if (arguments.length = = 1) {
Zero1 ();
} else{
Zero2 ();
}
}
It's really hard to see, even if we switch. Case, also not look ah.
Javascript arguments is not an array
Arguments is not always an array as we see it, sometimes it may not be.
Copy Code code as follows:
function Hello () {
Console.log (typeof arguments);
}
The type of arguments here is an object, although the type of the array is also an object, although we can convert it to an array
Copy Code code as follows:
var args = Array.prototype.slice.call (arguments);
But it also shows that this is not an array, it has only one property of array, that is, length. In addition to this, there are
Arguments.callee
Reference to the currently executing function.
Arguments.caller
Reference to the function of that invoked the currently executing function.
Arguments.length
Reference to the number of arguments passed to the function.