ES6 对象解构

解构是ES6新加的解构功能,可以使得我们获取数据更方便,从而提高日常编码效率。

1.解构用于变量声明

const Tom = {
    name: "Tom",
    age: 25,
    family: {
        mother: "Norah",
        father: "Richard",
        brother: "Howard"
    }
}
const { name, age } = Tom
console.log(name)  //  Tom Jones
console.log(age)  // 25
const { mother,father,brother } = Tom.family
console.log(mother) //Norah
console.log(father) //father
console.log(brother) //Howard

注意:不能提前声明解构过的变量,如果要声明如下方式

let Tom = {
    name: "Tom",
    age: 25
}
name = 'Bom';
age = 20;
console.log(name) //Bom
console.log(age) //20
({ name, age } = Tom) //该方式声明,会被解析成代码块
console.log(name)  //Tom
console.log(age) //25   

以上代码的逻辑为:预先定义的变量name和age分别被初始化为’Bom’和20之后,又用node对象的属性,重新赋值给name和age变量。解构赋值的语法要求,一定要用一对小括号()包裹整个解构赋值表达式。

2.解构对象属性赋值给不同名变量

当解构对象属性变量被使用时,可以赋值不同变量名

const Tom = {
    name: "Tom",
    age: 25,
    family: {
        mother: "Norah",
        father: "Richard",
        brother: "Howard"
    }
}
const father = "abc";
//当father变量被使用时
const { mother, father: f, broter } = Tom.family // 对father 变量重新命名
console.log(f) // Richard

3.给解构的变量设置默认值

如果我们在解构声明变量时,定义了对象中不存在的属性,那么这个变量的值为undefined。我们可以给变量设置默认值,当对象中没有对应的属性时,这个变量的值就是设置的默认值。

const Tom = {
    name: "Tom",
    age: 25,
    family: {
        mother: "Norah",
        father: "Richard",
        brother: "Howard"
    }
}
const { mother,father,brother, sister = "have no sister " } = Tom.family
console.log(sister) // have no sister

4.嵌套对象的解构

const Tom = {
    name: "Tom",
    age: 25,
    family: {
        mother: "Norah",
        father: "Richard",
        brother: {
		name:"Bom",
		age:18
		}
    }
}
const { family:{ brother} } = Tom;
console.log(brother.name);// Bom

你可能感兴趣的:(ES6)