九.对象解构

当我们要得到Tom对象的属性的时候,

es5写法:

const name = Tom.name
const age = Tom.age
const ..... console.log(name,age); // Tom Jones 25

  

es6写法:

const { name, age} = Tom;

console.log( name );    // Tom Jones
console.log( age );       // 25

  

需要注意的是: 在次之前是不能声明同名变量的,如果要提前声明 需要这样做

let name ;
({ name, age } = Tom);

console.log(name);
console.log(age);

  

es6对象解构中,可以嵌套

const { father, mother, brother } = Tom.family;

console.log( father );
console.log( mother );
console.log( brother );


// 假设 father这个变量已经被使用过了,那我们需要赋值一个新变量
const father = 'Dad';
const { father: f, mother, brother } = Tom.family;

console.log(father);  //father is not defined
console.log(f);     // Richard Jones
console.log(mother);  // Norah Jones
console.log(brother);  //Howard Jones

  

原文地址:https://www.cnblogs.com/wangRong-smile/p/11926324.html