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

函数参数的解构赋值

function sum(x, y) {
    return x + y;
}
sum(1,2);//3

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

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

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]

 

posted @ 2016-12-31 00:27  web全端小屋  阅读(268)  评论(0编辑  收藏  举报