Javascript 简明教程

JavaScript - Nullish Coalescing Operator

Nullish Coalescing Operator

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

The Nullish Coalescing operator in JavaScript is represented by two question marks (??). It takes two operands and returns the first operand if it is not null or undefined. Otherwise, it returns the second operand. It is a logical operator introduced in ES2020.

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

In many cases, we can have the null or empty values stored in the variables, which can change the behavior of the code or generate errors. So, we can use the Nullish Coalescing operator to use the default values when a variable contains falsy values.

Syntax

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

We can follow the syntax below to use the Nullish Coalescing operator.

op1 ?? op2

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

The nullish coalescing operator (??) returns the second operand (op2) if the first operand (op1) is null or undefined. Otherwise, the 'res' variable will contain 'op2'.

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

The above syntax is similar to the below code.

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

Examples

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

Let’s undersand the nullish coalescing operator in details with the help of some examples.

Example: Handling null or undefined

在下面的示例中, x 的值为 null 。我们使用 x 作为第一个操作数,5 作为第二个操作数。您可以在输出中看到 y 的值为 5,因为 x 为 null 。您可以将 undefined 赋值给变量。

In the example below, the value of the x is null. We used the x as the first operand and 5 as the second. You can see in the output that the value of y is 5, as x is null. You can assign undefined to the variable.

<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>

它将产生以下结果 −

It will produce the following result −

The value of y is: 5

Example: Handling null or undefined in Arrays

在下面的示例中,我们定义了一个包含数字的数组。我们使用空数组 ([]) 作为第二个操作数。因此,如果 arr 为 null 或 undefined,我们会将一个空数组赋值给 arr1 变量。

In the example below, we have defined an array containing numbers. We used the empty array ([]) as a second operand. So, if arr is null or undefined, we assign an empty array to the arr1 variable.

<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>

它将产生以下结果:

It will produce the following result –

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

Example: Accessing Object Properties

在下面的示例中,我们创建了包含与移动相关的属性的对象。在此之后,我们访问对象属性并使用值初始化变量。该对象不包含“brand”属性,因此代码使用“Apple”初始化“brand”变量,您可以在输出中看到这一点。

In the example below, we created the object containing the mobile-related properties. After that, we access the properties of the object and initialize the variables with value. The object doesn’t contain the 'brand' property, so the code initializes the 'brand' variable with the 'Apple', which you can see in the output.

通过这种方式,在访问具有不同属性的对象的属性时,我们可以使用空值合并运算符。

In this way, we can use the Nullish Coalescing operator while accessing the properties of objects having different properties.

<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>

它将产生以下结果:

It will produce the following result –

The product is Mobile of the brand Apple

Short-Circuiting

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

Like Logical AND, and OR operators, the Nullish Coalescing operator doesn’t evaluate the right-hand operand if the left-hand operand is neither null nor undefined.

Using ?? with && or ||

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

When we use the ?? operator with logical AND or OR operators, we should use the parenthesis to explicitly specify the precedence.

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

Example

在下面的示例中,我们对 OR 运算符 (||) 和 AND 运算符 (&&) 使用了空值合并运算符。

In the example below, we have used nullish coalescing operator with OR operator (||) and AND operator (&&).

<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 above program will produce the following result −

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