变量的解构赋值→对象的解构赋值
程序员文章站
2022-07-02 09:46:24
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>对象的解构赋值</title>
</head>
<body>
<script>
const Tom = {
name: 'xyz',
age: 21,
family: {
mother: 'lzl',
father: 'xh',
brother: 'xzh'
}
}
/*
获取对象里面的属性值
*/
// ES5
const name1 = Tom.name;
const age1 = Tom.age;
console.log(name1);
console.log(age1);
//ES6
const { name, age } = Tom;
console.log(name);
console.log(age);
/*
对象解构语法嵌套
*/
//ES5
const mother1 = Tom.family.mother;
console.log(mother1);//lzl
//ES6
const {mother}=Tom.family;
console.log(mother);//lzl
//注意:如果你的项目里面已经通过const声明了mother,你可以像下面这么操作
const mother2='have been used';
//const{mother:mother2}=Tom.family;//报错:Identifier 'mother2' has already been declared
const{mother:mother3}=Tom.family;
console.log(mother3);//lzl
/*
如果我现在获取Tom对象里面sister属性值,但是里面没有
*/
const {mother:mother4,sister}=Tom.family;
console.log(sister);//undefined
/*
遇到这种情况,你可以直接给点提示,操作如***意只有在sister1属性值没有情况下,
也就undefined的情况下才会显示你给的默认值也就是我说的提示“have no sister”,如果
sister1属性值为null、false、0都不会显示默认值“have no sister”
*/
const {mother:mother5,sister1="have no sister"}=Tom.family;
console.log(sister1);
</script>
</body>
</html>
上一篇: js变量解构赋值