JavaScript - 解構賦值



解構賦值

在 JavaScript 中,解構賦值是一種表示式,它允許我們解包陣列或物件中的值並將其儲存到單個變數中。它是一種將陣列值或物件屬性賦值給變數的技術。

解構賦值語法是在 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

如果陣列不包含動態數量的元素,以上程式碼將有效。如果陣列包含 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

示例:巢狀陣列解構

在下面的示例中,我們建立了一個巢狀陣列。為了訪問這些元素,我們使用了巢狀陣列解構賦值。請嘗試以下示例 -

<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

物件解構賦值

您可以按照以下語法使用解構賦值來解包物件元素。

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

示例:巢狀物件解構

在下面的示例中,我們定義了一個名為 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

下一步是什麼?

在接下來的章節中,我們將詳細學習以下概念。

  • 陣列解構 - 解包陣列元素。

  • 物件解構 - 解包物件屬性。

  • 巢狀解構 - 解包巢狀陣列元素和巢狀物件。

廣告