1. length property function
length
Is an attribute value of the object function, the function refers to the number of parameters must be passed, i.e., the number of formal parameters.
Parameter does not include the number of the remaining number of parameters, including only the first number of parameters have default values before.
Contrast that arguments.length
is the number of actual parameter passing when the function is called.
demo1:
function foo(a, b=1, c) {
console.log(arguments.length); // 3
// 形参的数量,仅包括第一个具有默认值之前的参数个数
console.log(foo.length); // 1
}
foo(1, 2, 3)
复制代码
demo2:
function foo(a, ...args) {
console.log(arguments.length); // 3
console.log(args); // [ 2, 3 ]
// 形参的数量不包括剩余参数个数
console.log(foo.length); // 1
}
foo(1, 2, 3)
复制代码
Note: rest parameters must be in the final surface, otherwise it will error.
2. arguments relationship between the parameter and
2.1 strict mode
argument represents an array of arguments class object, it always changes, there is a parameter, and corresponds to a mapping relationship, a change, the other will automatically follow changes named parameter changes.
function fn(a, b) {
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
a = 10;
b = 20;
// 改变了形参的值,arguments自动更新
console.log(arguments[0]); // 10
console.log(arguments[1]); // 20
arguments[0] = 100;
arguments[1] = 200;
// 改变了arguments的值,形参自动更新
console.log(a); // 100
console.log(b); // 200
}
fn(1, 2)
复制代码
2.2 Strict Mode
When the function has a default argument wording, changing the values of a and b, and will not affect the arguments object, and can not enter strict mode.
function fn(a, b) {
'use strict';
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
a = 10;
b = 20;
// 改变了形参的值,但不影响arguments
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
arguments[0] = 100;
arguments[1] = 200;
// 改变了arguments的值,但不影响形参
console.log(a); // 10
console.log(b); // 20
}
fn(1, 2)
复制代码
2.3 default parameters and parameter arguments does not matter
When an arbitrary function of a parameter has a default value, and all arguments parameter mapping relationship no longer exists. In this case strict mode and can not enter, otherwise it will error.
function fn(a, b=3) {
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
a = 10;
b = 20;
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
arguments[0] = 100;
arguments[1] = 200;
console.log(a); // 10
console.log(b); // 20
}
fn(1, 2)
复制代码
function fn(a, b=3) {
'use strict';
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
a = 10;
b = 20;
console.log(arguments[0]); // 1
console.log(arguments[1]); // 2
arguments[0] = 100;
arguments[1] = 200;
console.log(a); // 10
console.log(b); // 20
}
fn(1, 2)
// 报错:
// SyntaxError: Illegal 'use strict' directive in function // with non-simple parameter list
复制代码
Reproduced in: https: //juejin.im/post/5cf9ff2be51d4556dc2935f6