JS 对象解构赋值
程序员文章站
2022-03-04 23:45:05
...
结构赋值:顾名思义,就是先把对象结构拆开,然后再获取到属性值,把值赋值给变量使用,减少代码编写量,例子如下:
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>js对象结构赋值</title>
</head>
<body>
</body>
<script>
var obj = {
name: "李四",
age: "20",
}
var { name: a, age: b } = obj
console.log(a, b); //李四 20
//含义是从obj对象中找到name,age属性,分别赋值给a,b;
//以上写法也可以简写如下:
var { name, age } = obj; //等价于var { name:name, age:age } = obj;
console.log(name, age); //李四 20
//嵌套对象结构赋值如下:
var obj = {
name: "张三",
age: "18",
newObj: {
sex: "男",
hobby: "shopping"
}
}
var { newObj } = obj;
var { sex, hobby } = newObj;
console.log(sex, hobby); //男 shopping
//以上写法也可以简写如下:
var { newObj: { sex, hobby } } = obj
console.log(sex, hobby); //男 shopping
</script>
</html>