解构

对象解构

为了方便一次性取出对象中的多个值,而不需要一一的取值赋值

const fk = {
    name: "fankai",
    age: 26,
    family: {
        farther: "fkfarther",
        mother: "fkmother",
        brother: "lyy"
    }
}

常用的对象解构

const {name, age} = fk
console.log(name) //fankai
console.log(name) //26

//当变量已经被声明过
let name
//使用括号括起来 否则js会认为是语句
({name, age} = fk)

使用与属性名不同的变量名

const {farther: far, mother: mon, brother} = fk.family
console.log(far)

当变量对应属性不存在时(即必须为undefined),使用默认值

const {farther, sister = "hava no sisiter"} = fk.family
console.log(sister) //hava no sisiter

数组解构

可以一次性从数组中取出多个值

const numbers = ["one", "two", "three", "four"]

//数组解构
const [a, b] = numbers
console.log(a) //one
console.log(b) //two

//如果有可以用空,来越过数组中变量
const [m, ,n] = numbers
console.log(m) //one
console.log(n) //three

//...onthers 来获取剩下所有值
const [c, ...others] = numbers
console.log(c) //one
console.log(others) //["two", "three", "four"]

//当不存在该值 即 该值为undefined时 使用默认值
const [d, g, , ,f="five"] = numbers
console.log(f) //five