(5)ES6解构赋值-函数篇

时间:2022-06-05 20:03:38

函数参数的解构赋值

function sum(x, y) {
return x + y;
}
sum(1,2);// //解构赋值
function sum([x, y]) {
return x + y;
}
console.log( sum([1,2]) );//

函数参数解构赋值的默认值

function fun({x = 0, y = 0} = {}) {
return [x, y];
} console.log( fun({}) ); //[0,0]
console.log( fun() ); //[0,0]
console.log( fun({x: 100}) ); //[100,0]
console.log( fun({x: 100, y: 200}) ); //[100,200]

函数参数的解构赋值的默认值undefined

function fun({x, y} = { x:0, y:0 }) {
return [x, y];
} console.log( fun({}) ); //[undefined,undefined]
console.log( fun() ); //[0,0] 没传参数实际上是对象的解构赋值
console.log( fun({x: 100}) ); //[100,undefined]
console.log( fun({x: 100, y: 200}) ); //[100,200]