解构赋值用在函数参数中的一点特性

//一个同时拥有参数默认值和解构赋值默认值的方法
function a({a=1,b=2}={a:3,b:4})
{
    console.log({a,b});
}

a() // 使用对象的默认值 {a: 3, b: 4}
a(undefined) // {a: 3, b: 4} 传入undefined等同于没传

a({}) // 使用value的默认值 {a: 1, b: 2}
a(10000) // 传入非对象时等同于传入空对象 {a: 1, b: 2}
a({a:100}) // 使用部分value的默认值 {a: 100, b: 2}

a(null) // TypeError: Cannot destructure property `a` of 'undefined' or 'null'

a({a:undefined}) // undefined 会被忽略,等同于没有该键值 {a: 1, b: 2} 
a({a:null}) // 但null不会被忽略 {a: null, b: 2}

猜你喜欢

转载自www.cnblogs.com/wozho/p/10258710.html
今日推荐