ES6 允许为函数的参数设置默认值,即直接写在参数定义的后面。通常情况下,定义了默认值的参数,应该是函数的尾参数,函数的length属性,将返回没有指定默认值的参数个数
function log(x, y = 'World') {
console.log(x, y);
}
参数默认值可以与解构赋值的默认值,结合起来使用。
function foo({x, y = 5}) {
console.log(x, y);
}
ES6 引入 rest 参数(形式为...变量名),用于获取函数的多余参数,这样就不需要使用arguments对象了。
function add(...values) {}
add(2, 5, 3)
// function myFun (a, b, c = 0) {
// console.log(a, b, c);
// }
// 拓展运算符用在函数的参数的时候,叫rest参数
// let myFun = (a, ...b) => {
// console.log(a, b);
// }
// myFun(1, 2, 3, 4, 5);
// 参数解构
// let fun = ({ name, age = 0 }) => {
// console.log(name, age);
// }
// fun({ name: '张三' })
let fun = ([a, b, ...c]) => {
console.log(a, b, c);
}
fun([1, 2, 3, 4])