解构-参数解构

190 阅读1分钟

练习

// 打印身份信息
const user = {
    name: 'lisa',
    age: 20,
    sex: '女',
    address: {
        province: '江苏',
        city: '无锡'
    }
}

// 原来的写法
/*function print(user){
    console.log(`姓名:${user.name}`); // lisa
    console.log(`省份:${user.address.province}`); // 江苏
}*/

// 参数解构写法
function print({ name, address: { province } }) {
    console.log(`姓名:${user.name}`); // lisa
    console.log(`省份:${user.address.province}`); // 江苏
}
print(user);
// 传递一些参数,其他使用默认值

// function ajax(options){
// }

function ajax({
    method = 'get',
    url = '/'
}) {
    console.log(method, url)
}

ajax({
    url: '/abc'
})
// 特殊场景:ajax里不传东西,整个就是传递undefined;如果尝试从undefined和null里去解构会报错
// 如何解决:参数默认值-直接给参数传递默认值
function ajax({
    method = 'get',
    url = '/'
} = {}) {
    console.log(method, url)
}
ajax()