1、函数参数默认值
function add(a = 1, b = 2) {
//let a = 2; //报错,不能有同名的参数
//const b = 3; //报错,不能有同名的参数
return a + b
}
add(); // 3
add(3, 4); // 7
2、解构赋值 和 函数参数的结合使用
// 设置了解构赋值y的默认值
function output1({
x, y = 1}) {
console.log(x, y)
}
output1(); // 报错 TypeError: Cannot read property 'x' of undefined
output1({
}); // undefined 1
output1({
x: 1}); // 1 1
output1({
x: 1, y: 2}); // 1 2
// 设置了参数默认值 {x: 2, y: 3}
function output2({
x, y} = {
x: 2, y: 3}) {
console.log(x, y)
}
output2(); // 2 3
output2({
}); // undefined undefined
output2({
x: 1}); // 1 undefined
output2({
x: 1, y: 2}); // 1 2
// 设置了解构赋值 y的默认值, 及参数默认值 {}
function output3({
x, y = 1} = {
}) {
console.log(x, y)
}
output3(); // undefined 1
output3({
}); // undefined 1
output3({
x: 1}); // 1 1
output3({
x: 1, y: 2}); // 1 2
3、参数默认值的位置
function a1(x = 1, y, z) {
console.log(x, y, z)
}
a1(2, 3, 4); // 2 3 4
a1(2); // 2 undefined undefined
a1(, 3, 4); //报错
function a2(x, y = 3, z) {
console.log(x, y, z)
}
a2(2, 3, 4); // 2 3 4
a2(2); // 2 3 undefined
a2(, , 4); //报错
a2(, 3, 4); //报错
a2(2, , 4); //报错
function a3(x, y, z = 4) {
console.log(x, y, z)
}
a3(2, 3, 4); // 2 3 4
a3(2, 3); // 2 3 4
a3(2); // 2 undefined 4
a3(, 3, 4); //报错
a3(2, , 4); //报错
a3(, , 4); //报错
4、使用函数的length属性,获取函数第一个默认值的参数之前的 参数的个数
(function a1(x, y, z = 1, a, b, c = 3){
}).length; //2 第一个默认参数 z 之前的参数有 x, y
(function a2(x, y, a, b, z = 1, c = 3){
}).length; //4 第一个默认参数 z 之前的参数有 x, y, a, b
(function a3(x = 1, y, a, b, z = 1, c = 3){
}).length; //0 第一个默认参数 x 之前的参数是没有的
5、rest参数
function x(a, ...rest) {
// 注意,rest参数后面不能再有其他的参数,会报错
console.log(a, rest);
}
x(1,2,3,4,5,6,7,8,9,0); // 1 [2,3,4,5,6,7,8,9,0]
// 注意,rest参数后面不能再有其他的参数,会报错
function x1(...rest, b) {
console.log(rest, b);
}
// length不包括 rest参数
(function(a) {
}).length; // 1
(function(...a) {
}).length; // 0
(function(a, ...b) {
}).length; // 1
6、ES5的函数内部可以使用严格模式,ES6会报错
// ES5
function x() {
'use strict'; // 正确
console.log(1)
}
// ES6
function x1() {
'use strict'; // 报错
console.log(1)
}
就记录到这,祝大家开心~