实例演示对象与数组的解构
实例展示:
实例源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>实例演示对象与数组的解构</title>
</head>
<body>
<script>
// 1. 对象解构
const xiangmu = {
name: "卫生间翻新",
price: 8999,
area: "成都",
};
// 声明三个变量
let name, price, area;
name = "卫生间翻新";
price = 8999;
area = "成都";
console.log(name, price, area);
// 完全解构
({ name, price, area } = xiangmu);
console.log(name, price, area);
// 不完全解构
({ name, price, area, shifu } = xiangmu);
console.log(name, price, area, shifu);
// 默认值
({ name, price, area, shifu = "张三" } = xiangmu);
console.log(name, price, area, shifu);
// =======================================================================
// 2. 数组解构
const areas = ["成都", "北京", "上海", "深圳", "广州"];
let [张师傅, 李师傅, 王师傅, 马师傅, 周师傅] = areas;
console.log(张师傅, 李师傅, 王师傅, 马师傅, 周师傅);
// 完全解构
let [a, b, c, d] = ["张", "李", "王", "马"];
console.log(a, b, c, d);
// 不完全解构
[a, ...b] = ["张", "李", "王", "马"];
console.log(a, b);
// 未定义:
[a, b, c, d] = ["张", "李", "王"];
console.log(a, b, c, d);
// 默认值:
[a, b, c, d = "马师傅"] = ["张", "李", "王"];
console.log(a, b, c, d);
</script>
</body>
</html>
实例总结:
- 解构主要针对集合类型有意义,对象,数组
- 对象解构的语法形式是在一个赋值操作左边放置一个对象字面量
- 数组解构,使用的是数组字面量,且解构操作全部在数组内完成