参数
参数默认值 Default parameters
// 以前使用这种方法设置默认参数
function foo(enable) {
//如果没传参数则给enable赋值true,如果有参数则为参数
enable = enable === undefined ? true : enable;
console.log(enable);
}
foo();
// 现在可以使用默认参数方法
function foo(enable = true) {
//如果没传参数,则给enable赋值true,如果有参数则为参数
console.log(enable);
}
foo();
// 注意
function foo(enable = true, other) {
//如果传参数,则按照从前往后顺序给enable和other赋值,enable就会被赋值为1
// 所以可以把设置了默认值的参数放在后面,防止出错
console.log(enable);
}
foo(1);
剩余参数
function foo1(a,...others){
//others中存储的是数组,存储的是实参中没有被接收的
// 实参中的 1 被 a 接收,剩下的存储在others中
console.log(others);
}
foo1(1,2,3,4);
展开数组
const arr = [1,2,3,4,5];
//...展开数组
// 打印出的是数组中的每一项
console.log(...arr);