JavaScript 空值合併運算子



空值合併運算子

JavaScript 中的空值合併運算子用兩個問號 (??) 表示。它接受兩個運算元,如果第一個運算元不是nullundefined,則返回第一個運算元。否則,它返回第二個運算元。它是一個在 ES2020 中引入的邏輯運算子。

在許多情況下,變數中可能儲存空值或空值,這可能會改變程式碼的行為或產生錯誤。因此,當變數包含虛假值時,可以使用空值合併運算子使用預設值。

語法

可以使用以下語法使用空值合併運算子。

op1 ?? op2 

空值合併運算子 (??) 如果第一個運算元 (op1) 為nullundefined,則返回第二個運算元 (op2)。否則,'res' 變數將包含 'op2'。

上述語法類似於以下程式碼。

let res;
if (op1 != null || op1 != undefined) {
   res = op1;
} else {
   res = op2;
}

示例

讓我們藉助一些示例詳細瞭解空值合併運算子。

示例:處理 null 或 undefined

在下面的示例中,x 的值為null。我們使用 x 作為第一個運算元,5 作為第二個運算元。您可以在輸出中看到 y 的值為 5,因為 x 為null。您可以為變數賦值 undefined。

<html>
<body>
   <div id = "output"></div>
   <script>
      let x = null;
      let y = x ?? 5;
      document.getElementById("output").innerHTML = 
	  "The value of y is: " + y;
   </script>
   </body>
</html>

它將產生以下結果:

The value of y is: 5

示例:處理陣列中的 null 或 undefined

在下面的示例中,我們定義了一個包含數字的陣列。我們使用空陣列 ([]) 作為第二個運算元。因此,如果 arr 為 null 或 undefined,我們將空陣列賦值給 arr1 變數。

<html>
<body>
   <div id = "output"></div>
   <script>
      const arr = [65, 2, 56, 2, 3, 12];
      const arr1 = arr ?? [];
      document.getElementById("output").innerHTML = "The value of arr1 is: " + arr1;
   </script>
</body>
</html>

它將產生以下結果:

The value of arr1 is: 65,2,56,2,3,12

示例:訪問物件屬性

在下面的示例中,我們建立了包含移動相關屬性的物件。之後,我們訪問物件的屬性並使用值初始化變數。物件不包含 'brand' 屬性,因此程式碼使用 'Apple' 初始化 'brand' 變數,您可以在輸出中看到。

這樣,在訪問具有不同屬性的物件的屬性時,可以使用空值合併運算子。

<html>
<body>
   <div id = "output"></div>
   <script>
      const obj = {
         product: "Mobile",
         price: 20000,
         color: "Blue",
      }

     let product = obj.product ?? "Watch";
     let brand = obj.brand ?? "Apple";
     document.getElementById("output").innerHTML =
	 "The product is " + product + " of the brand " + brand;
   </script>
</body>
</html>

它將產生以下結果:

The product is Mobile of the brand Apple

短路

與邏輯 AND 和 OR 運算子一樣,如果左運算元既不是 null 也不是 undefined,則空值合併運算子不會評估右運算元。

將 ?? 與 && 或 || 一起使用

當我們將 ?? 運算子與邏輯 AND 或 OR 運算子一起使用時,應使用括號明確指定優先順序。

let x = 5 || 7 ?? 9; // Syntax Error
let x = (5 || 7) ?? 9; // works

示例

在下面的示例中,我們使用了與 OR 運算子 (||) 和 AND 運算子 (&&) 的空值合併運算子。

<html>
<body>
  <div id = "output"></div>
  <script>
    let x = (5 || 7) ?? 9;
    let y = (5 && 7) ?? 9;
    document.getElementById("output").innerHTML =
      "The value of x is : " + x + "<br>" + 
      "The value of y is : " + y;
</script>
</body>
</html>

上述程式將產生以下結果:

The value of x is : 5
The value of y is : 7
廣告