- 函数默认值
function log(x, y = 'world') {
console.log(x, y);
}
log('hello'); // hello world
log('hello', 'China'); // hello China
log('hello', ''); // hello
ES6函数写法的好处
-
阅读代码时可知哪些参数是可省略的,不用查看函数体或者文档。
-
利于代码优化,以后新版本即使没有删除该函数,也不会导致以前的代码无法运行。
变量默认声明
function log(x, y = 'world') {
console.log(x, y);
}
//默认x,y 是声明的。
function log(x, y = 'world') {
const x; //error
let y; // error
console.log(x, y);
}
函数不能有同名参数
function log(x, x, y = 'world') { // error
console.log(x, y);
}
function m1 ({x = 0, y = 0} = {}) {
return [x, y];
}
function m2 ({x, y} = { x: 0, y: 0}) {
return [x, y];
}
//m1参数默认值为空对象,设置了对象结构赋值的默认值
//m2参数默认值是一个具有具体属性的函数,没有设置对象结构赋值的默认值
console.log(m1()); //[0, 0]
console.log(m2()); //[0, 0]
console.log(m1({x: 3, y: 8})); //[3, 8]
console.log(m2({x: 3, y: 8})); //[3, 8]
console.log(m1({x: 3})); //[3, 0]
console.log(m2({x: 3})); //[3, undefined]
console.log(m1({})); //[0, 0]
console.log(m2({})); //[undefined, undefined]
console.log(m1({z: 3})); //[0, 0]
console.log(m2({z: 3})); //[undefined, undefined]
参数默认值的位置
- 1. 非尾部的参数设置默认值,实际上该参数无法省略。
function f(x = 1, y) {
return [x ,y];
}
console.log(f(, 1)); //error
console.log(f(null, 1)); //[null, 1]
console.log(f(undefined, 1));//[1, 1]
- 2. 参数有默认值时,无法只省略该参数而不省略其他参数
function f(x, y = 2, z) {
return [x, y, z];
}
console.log(f()); //[undefined, 2, undefined]
console.log(f(1)); //[1, 2, undefined]
console.log(f(2, , 8));//error