[ES6] 解构

对象解构

1. 什么是解构

将一个对象或者数组的某个属性提取到某个变量中

解构不会对被解构目标造成任何影响

const obj = {
    name: "Jim",
    age: "20",
    sex: "male",
    address: {
        country: "China",
        city: "Peking"
    }
}


let { name, age, sex, address } = obj;
console.log( name, age, sex, address )

2. 在解构中使用默认值

{同名变量 = 默认值}

let { name, age, sex, test = "test" } = obj;
console.log( name, age, sex, test )
// test等号后面就是默认值

3. 非同名属性解构

{属性名:变量名}

let { name, age: testAge, sex, test = "test" } = obj;
console.log( name, testAge, sex, test )

数组解构

使用方法和对象解构类似

const numbers = [1, 2, 3, 4, 5];

let [a, b, ...c] = numbers; // 使用展开运算符,把剩下的数组数据保存在c里面
// 注意,展开运算符只能用在最后一个
// let [...a, b, ...c] = numbers   这么写会报错
console.log(a,b,c)

两个变量值的交换

let a = 1, b = 2;
[b, a] = [a, b]
console.log(a, b)   // a = 2, b = 1

练习:解构出第二条评论的用户名和评论内容

const article = {
    title: "文章标题",
    content: "文章内容",
    comments: [{
        content: "评论1",
        user: {
            id: 1,
            name: "用户名1"
        }
    }, {
        content: "评论2",
        user: {
            id: 2,
            name: "用户名2"
        }
    }]
}

// 解构出第二条评论的用户名和评论内容

let { comments: [, {
        content,
        user: {
            name
        }
    }]
} = article
console.log( content, name)   // 评论2 用户名2

参数解构

const obj = {
    name: "Jim",
    age: "20",
    sex: "male",
    address: {
        country: "China",
        city: "Peking"
    }
}
// 参数传过来的是个对象{},直接在这里解构就可以了,数组同理[]
function print ({ name, age, sex, address: {
    country, city
}}) {
    console.log(name)
    console.log(age)
    console.log(sex)
    console.log(country)
    console.log(city)
}
print(obj)
// ES5
// function ajax (options) {
//     const defaultOption = {
//         method: "get",
//         url:"/"
//     }
//     const opt = {
//         ...defaultOption,
//         ...options
//     }

//     console.log(opt)
// }

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

ajax({
    method: "POST"
})

你可能感兴趣的:([ES6] 解构)