Javascript 简明教程

JavaScript - Nullish Coalescing Operator

Nullish Coalescing Operator

JavaScript 中的 Nullish Coalescing 运算符由两个问号 (??) 表示。它接受两个操作数,如果第一个操作数不是 nullundefined ,则返回第一个操作数。否则,它返回第二个操作数。它是 ES2020 中引入的逻辑运算符。

在很多情况下,我们会让变量中存储空值或空值,这会改变代码的行为或生成错误。因此,我们可以在变量包含错误值时使用空值合并运算符来使用默认值。

Syntax

我们可以按照以下语法使用空值合并运算符。

op1 ?? op2

nullish coalescing 运算符 (??) 在第一个操作数 (op1) 为 nullundefined 时,返回第二个操作数 (op2)。否则,“res”变量将包含“op2”。

上述语法类似于下面的代码。

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

Examples

让我们通过一些示例详细了解空值合并运算符。

Example: Handling null or 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

Example: Handling null or undefined in Arrays

在下面的示例中,我们定义了一个包含数字的数组。我们使用空数组 ([]) 作为第二个操作数。因此,如果 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

Example: Accessing Object Properties

在下面的示例中,我们创建了包含与移动相关的属性的对象。在此之后,我们访问对象属性并使用值初始化变量。该对象不包含“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

Short-Circuiting

与逻辑 AND 和 OR 运算符类似,如果左操作数既不是 null 也不是 undefined,空值合并运算符不会计算右操作数。

Using ?? with && or ||

当我们对逻辑 AND 或 OR 运算符使用 ?? 运算符时,我们应该使用括号明确指定优先级。

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

Example

在下面的示例中,我们对 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