JavaScript - 可選鏈



JavaScript 中的可選鏈允許您訪問物件的巢狀屬性和方法,而無需檢查每個屬性是否存在。這有助於使您的程式碼更簡潔且更易於閱讀。

可選鏈運算子 (?.) 用於在 JavaScript 中實現可選鏈。它放在您要訪問的屬性或方法之前。如果屬性或方法不存在,表示式將評估為 undefined,而不是丟擲錯誤。

不存在的屬性問題

讓我們透過不存在的屬性問題來了解 JavaScript 中可選鏈的需求。

在使用 JavaScript 中的物件時,您可能擁有具有動態屬性的物件。某些屬性還包含物件作為值,稱為巢狀物件。

如果您嘗試訪問其父級不存在的巢狀屬性,JavaScript 可能會丟擲錯誤。

例如,

const parent = {
    child: {
        name: "Smith",
    }
}
const name = parent.child.name;

父物件包含 'ch' 屬性,而 'ch' 屬性包含巢狀物件作為值。

在程式碼中,您訪問巢狀物件 'child' 的 'name' 屬性,但 'child' 屬性在父物件中不存在。因此,當您訪問未定義的屬性時,JavaScript 將丟擲以下錯誤。

Uncaught TypeError: Cannot read properties of undefined

為了解決上述問題,在 ES11 之前使用 '&&' 運算子。

例如,

if (parent.child && parent.child.name) {
   // access parent.child.name here
}

在上面的程式碼中,我們首先檢查 parent.child 是否存在。如果是,我們訪問其 name 屬性以避免錯誤。

您找到了解決方案,但是如果您需要訪問物件第 4 或第 5 層的屬性怎麼辦?您需要使用多個 && 運算子並編寫複雜的程式碼。

在這裡,可選鏈運算子 (?. ) 出現以輕鬆解決不存在的屬性問題。

什麼是 JavaScript 中的可選鏈?

在 JavaScript 中,可選鏈運算子 (?. ) 引入於 ECMAScript 2020 (ES2020)。它提供了訪問物件屬性、陣列元素等最佳方式。

可選鏈非常類似於用於訪問物件巢狀屬性的普通鏈。它在訪問物件屬性之前檢查巢狀屬性是否存在,以避免錯誤。

語法

您可以按照以下語法在 JavaScript 中使用可選鏈運算子。

Obj?.prop1?.nestedprop; // Accessing nested properties
Obj?.[expression]; // Accessing object property via expression
Array?.[index]; // Accessing array element
funcName?.(); // Executing the funciton 
  • 在以上語法中,如果物件 obj 存在,它將訪問屬性 prop1。程式碼再次檢查 obj 物件中是否存在 prop1 屬性,如果存在,它將訪問 nestedProp 屬性。否則,它將停止程式碼執行以避免錯誤。

  • 您還可以使用表示式和可選鏈來訪問物件屬性值。

  • 可選鏈還可以用於訪問陣列元素和執行函式。

返回值

如果屬性不存在,可選鏈將返回 undefined 而不丟擲任何錯誤。

示例

在下面的示例中,car 物件包含巢狀物件 'info'。info 物件包含 color 和 price 屬性。

我們嘗試使用可選鏈訪問 info 物件的 price 屬性,它返回 5000000。

之後,我們嘗試使用可選鏈訪問 car 物件的 engine 屬性的 gears 屬性。在輸出中,您可以看到它返回 undefined 而不是丟擲錯誤。

<html>
<body>
   <div id = "output1">The price of the Audi Q6 is: </div>
   <div id = "output2">Total gears in the Audi Q6 is: </div>
   <script>
      const car = {
         brand: "Audi",
         model: "Q6",
         info: {
            price: 5000000,
            color: "Black",
         }
      }
      document.getElementById("output1").innerHTML += car.info?.price;
      document.getElementById("output2").innerHTML += car.engine?.gears;
   </script>
</body>
</html>

輸出

The price of the Audi Q6 is: 5000000
Total gears in the Audi Q6 is: undefined

帶有函式呼叫的可選鏈

在 JavaScript 中,您還可以將可選鏈與函式呼叫一起使用。如果函式未定義,它將返回 undefined。否則,程式碼將執行該函式。

示例

在下面的程式碼中,我們使用可選鏈與物件方法。

car 物件包含 getBrand() 方法。我們在執行 getBrand() 方法時使用了可選鏈,它返回 'Audi'。

此外,我們嘗試使用可選鏈執行 car 物件的 getColor() 方法。它返回 undefined,因為 car 物件不包含 getColor() 方法。

<html>
<body>
   <div id = "output1">The brand of the car is: </div>
   <div id = "output2">The color of the car is: </div>
   <script>
      const car = {
         getBrand() {
            return "Audi";
         },
      }
      document.getElementById("output1").innerHTML += car.getBrand?.();
      document.getElementById("output2").innerHTML += car.getColor?.();
   </script>
</body>
</html>

輸出

The brand of the car is: Audi
The color of the car is: undefined

帶有表示式的可選鏈

在使用表示式或陣列元素訪問物件屬性時,可以使用可選鏈。

示例

在下面的程式碼中,animal 物件包含 name 和 info 屬性。info 屬性再次包含一個巢狀物件,該物件具有 legs 和 tail 屬性。

我們使用可選鏈和表示式訪問物件屬性。您可以看到它在程式碼中列印輸出而沒有丟擲任何錯誤,即使 'specs' 屬性在 animal 物件中不存在。

<html>
<body>
   <div id = "output1">Total number of legs of the tiger is: </div>
   <div id = "output2">The color of the tiger is: </div>
   <script>
      const animal = {
         name: "Tiger",
         info: {
            legs: 4,
            tail: 1,
         }
      }
      document.getElementById("output1").innerHTML += animal.info?.["legs"];
      document.getElementById("output2").innerHTML += animal.specs?.["color"];
   </script>
</body>
</html>

輸出

Total number of legs of the tiger is: 4
The color of the tiger is: undefined

帶有 "delete" 運算子的可選鏈

JavaScript delete 運算子用於刪除物件屬性。如果您嘗試刪除不存在的屬性,程式碼將丟擲錯誤。因此,您可以將可選鏈運算子與 delete 運算子一起使用。

示例

在下面的程式碼中,我們使用 delete 運算子刪除巢狀 info 物件的 legs 屬性和 'specs' 巢狀物件的 tail 屬性,並使用可選鏈訪問屬性。

animal 物件不包含 specs 屬性。儘管如此,由於可選鏈,程式碼仍在執行而沒有任何錯誤。

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const animal = {
         name: "Tiger",
         info: {
            legs: 4,
            tail: 1,
         }
      }
      delete animal.info?.legs;
      delete animal.sepcs?.tail;
      document.getElementById("demo").innerHTML = 
      "Updated object is: " + JSON.stringify(animal);
   </script>
</body>
</html>

輸出

Updated object is: {"name":"Tiger","info":{"tail":1}}

可選鏈的短路

在 JavaScript 中,短路的含義是每當您遇到錯誤時,停止程式碼執行。您可以使用可選鏈訪問物件的每個巢狀屬性以避免任何錯誤並在錯誤時停止程式碼執行。

示例

在下面的程式碼中,animal 物件包含 info 物件,info 物件包含 legs 物件。我們使用可選鏈來訪問每個巢狀屬性。因此,如果任何屬性不存在,它將返回 undefined 並避免錯誤。

<html>
<body>
   <div id = "output1">The size of the first leg is: </div>
   <div id = "output2"> The size of the third leg is: </div>
   <script>
      const animal = {
         name: "Tiger",
         info: {
            legs: {
               first: 1.32,
               second: 1.31,
            },
            tail: 1,
         }
      }
      document.getElementById("output1").innerHTML += animal?.info?.legs?.first;
      document.getElementById("output2").innerHTML += animal?.specs?.legs?.third;
    </script>
</body>
</html>

輸出

The size of the first leg is: 1.32
The size of the third leg is: undefined

可選鏈與空值合併運算子

當任何物件屬性不存在時,可選鏈將停止程式碼執行並返回 undefined。如果將 JavaScript 空值合併運算子與它一起使用,則可以在物件屬性不存在時返回預設值。

示例

在下面的程式碼中,我們嘗試訪問 'animal' 物件的 'specs' 物件的 color 屬性。這裡,'specs' 不存在於 animal 物件中。因此,它返回 'red',因為我們使用了空值合併運算子。

<html>
<body>
   <div id = "output">The color of the animal is: </div>
   <script>
      const animal = {
         name: "Tiger",
         info: {
            legs: 2,
            tail: 1,
         }
      }
      animal.info?.legs;
      const color = animal?.spec?.color ?? "Red";
      document.getElementById("output").innerHTML += color;
   </script>
</body>
</html>

輸出

The color of the animal is: Red

簡單來說,您可以在需要訪問動態物件的屬性以避免錯誤的任何地方使用可選鏈運算子。

廣告