解构赋值
在 JavaScript 中,解构赋值(destructuring assignment) 是一个表达式,它允许我们从数组或对象中解包值并将它们存储在单个变量中。这是一种为变量分配数组值或对象属性的技术。
解构赋值语法在 ECMAScript 6 (ES6) 中引入。在 ES6 之前,开发人员需要手动解压缩对象属性,如下例所示。
ES6 之前的数组解包
在下面的示例中,'arr' 数组包含水果名称。之后,我们创建了不同的变量并为变量分配了数组元素。
<html>
<body>
<p id = "output"> </p>
<script>
const arr = ["Apple", "Banana", "Watermelon"];
const fruit1 = arr[0];
const fruit2 = arr[1];
const fruit3 = arr[2];
document.getElementById("output").innerHTML =
"fruit1: " + fruit1 + "<br>" +
"fruit2: " + fruit2 + "<br>" +
"fruit3: " + fruit3;
</script>
</body>
</html>
输出
fruit1: Apple
fruit2: Banana
fruit3: Watermelon
fruit2: Banana
fruit3: Watermelon
如果数组不包含动态数量的元素,则上面的代码将起作用。如果数组包含 20+ 个元素怎么办?你会写 20 行代码吗?
这里,解构赋值的概念出现了。
数组解构赋值
你可以按照下面的语法使用解构赋值来解包数组元素。
const [var1, var2, var3] = arr;
在上面的语法中,'arr' 是一个数组。var1、var2 和 var3 是用于存储数组元素的变量。您也可以以类似方式解压缩对象。
例下面的示例实现了与上述示例相同的逻辑。在这里,我们使用了解构赋值来解包数组元素。该代码提供与上一个示例相同的输出。
<html>
<body>
<p id = "output"> </p>
<script>
const arr = ["Apple", "Banana", "Watermelon"];
const [fruit1, fruit2, fruit3] = arr;
document.getElementById("output").innerHTML =
"fruit1: " + fruit1 + "<br>" +
"fruit2: " + fruit2 + "<br>" +
"fruit3: " + fruit3;
</script>
</body>
</html>
输出
fruit1: Apple
fruit2: Banana
fruit3: Watermelon
fruit2: Banana
fruit3: Watermelon
示例:嵌套数组解构
在下面的示例中,我们创建了一个嵌套数组。为了访问这些元素,我们使用了嵌套数组解构赋值。请尝试以下示例 –
<html>
<body>
<p id = "output"> </p>
<script>
const arr = ["Apple", ["Banana", "Watermelon"]];
const [x, [y, z]] = arr;
document.getElementById("output").innerHTML =
x + "<br>" +
y + "<br>" +
z ;
</script>
</body>
</html>
输出
Apple
Banana
Watermelon
Banana
Watermelon
对象解构赋值
您可以按照以下语法使用解构赋值来解压缩对象元素。
const {prop1, prop2, prop3} = obj;
在上面的语法中,'obj' 是一个对象。prop1、prop2 和 prop3 是用于存储对象属性的变量。
例下面的示例实现了与数组解构赋值示例相同的逻辑。在这里,我们使用了解构赋值来解包对象元素。
<html>
<body>
<div id = "output1"> </div>
<div id = "output2"> </div>
<script>
const fruit = {
name: "Apple",
price: 100,
}
const {name, price} = fruit;
document.getElementById("output1").innerHTML = "fruit name: " + name;
document.getElementById("output2").innerHTML = "fruit price: " + price;
</script>
</body>
</html>
输出
fruit name: Apple
fruit price: 100
fruit price: 100
示例:嵌套对象解构
在下面的示例中,我们定义了一个名为 person 的嵌套对象,该对象具有两个属性 age 和 name。name 属性包含两个名为 fName 和 lName 的属性。我们使用嵌套解构来访问这些属性。
<html>
<body>
<div id = "output"> </div>
<script>
const person = {
age: 26,
name: {
fName: "John",
lName: "Doe"
}
}
// nested destructuring
const {age, name: {fName, lName}} = person;
document.getElementById("output").innerHTML =
"Person name: " + fName + " " + lName + "<br>"+
"Person age: " + age;
</script>
</body>
</html>
输出
Person name: John Doe
Person age: 26
Person age: 26
下一步是什么?
在接下来的章节中,我们将学习以下关于被拘留者的概念。
- 数组解构 - 解包数组元素。
- 对象解构 - 解包对象属性。
- 嵌套解构 - 解包嵌套数组元素和嵌套对象。