JavaScript - 空值合并运算符
空值合并运算符
JavaScript 中的 空值合并 运算符用两个问号 (??) 表示。它接受两个操作数,如果第一个操作数不为 null 或 undefined,则返回第一个操作数。否则,返回第二个操作数。它是 ES2020 中引入的逻辑运算符。
在很多情况下,变量中可能会存储 null 或空值,这可能会改变代码的行为或产生错误。因此,当变量包含假值时,我们可以使用空值合并运算符来使用默认值。
语法
我们可以按照以下语法使用空值合并运算符。
op1 ?? op2
如果第一个操作数 (op1) 为 null 或 undefined,则 空值合并 运算符 (??) 返回第二个操作数 (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
短路
与逻辑与和或运算符类似,如果左侧操作数既不是 null 也不是 undefined,则空值合并运算符不会计算右侧操作数的值。
将 ?? 与 && 或 || 一起使用
将 ?? 运算符与逻辑与或或运算符一起使用时,应使用括号明确指定优先级。
let x = 5 || 7 ?? 9; // 语法错误 let x = (5 || 7) ?? 9; // 有效
示例
在下面的示例中,我们使用了空值合并运算符以及或运算符 (||) 和与运算符 (&&)。
<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

