1. What arguments
In simple terms: Arguments is an array-like object corresponding to the arguments passed to the function
Arguments objects are local variables available in all (non-arrow) functions. You can use arguments objects to refer to function arguments in functions. This object contains each argument passed to the function, the first at index 0. For example, if a function passes three arguments, you can refer to them as follows:
arguments[0]
arguments[1]
arguments[2]
Copy the code
Parameters can also be set:
arguments[0] = 'value';
Copy the code
Arguments is an object, not an Array. It is similar to Array, but does not have any Array attributes other than the Length attribute and index element. For example, it has no POP method. But it can be converted to a real Array:
So it’s common to see code like this:
// Since arguments are not Array, you can't use Array methods, so you can convert arguments to arrays using this method
var args = [].slice.call(arguments); / / way
var args = Array.prototype.slice.call(arguments); 2 / / way
// Here is the syntax provided by ES6
let args = Array.from(arguments) / / way
let args = [...arguments]; 2 / / way
Copy the code
2. Arguments on properties
- Arguments.callee: points to the currently executed function (in strict mode, ECMAScript version 5 (ES5) Prohibited use
arguments.callee()
) - Argunments. length: Points to the number of arguments passed to the current function
- Arguments. caller: Has been removed
Use arguments in combination with residual arguments, default arguments, and destruct assignment arguments
- In strict mode,The remaining parameters,The default parametersandDeconstruction assignmentThe existence of parameters does not change
arguments
Object behavior, but not in strict mode
function func(a) {
arguments[0] = 99; Arguments [0] also update a
console.log(a);
}
func(10); / / 99
/ / and
function func(a) {
a = 99; // Add arguments[0]
console.log(arguments[0]);
}
func(10); / / 99
Copy the code
- When the function is not in strict modeThere is nocontainsThe remaining parameters,The default parametersandDeconstruction assignment, then
arguments
Values in objectswillTrace the value of the parameter (and vice versa). Look at the following code:
function func(a = 55) {
arguments[0] = 99; // updating arguments[0] does not also update a
console.log(a);
}
func(10); / / 10
//
function func(a = 55) {
a = 99; // updating a does not also update arguments[0]
console.log(arguments[0]);
}
func(10); / / 10
function func(a = 55) {
console.log(arguments[0]);
}
func(); // undefined
Copy the code