JavaScript 中的逻辑无效赋值 ??=
这是javascript引入的新运算符。该运算符由x ??= y表示,称为逻辑空值赋值运算符。只有当x的值为null时,y 的值才会分配给x 方法 如果 x 的值为null或未定义,则 y 的值将分配给 x。
句法 :
x ??= y
Means : x ?? (x = y)
示例 1:
Javascript
let x = 12;
let y = null;
let z = 13;
// The value of x will become
// unchanged because x is not nullish.
x ??= z;
// The value of y will be
// changed because y is nullish.
y ??= z;
console.log(x) // 12
console.log(y) // 13
Javascript
let x = {
name : "Ram"
}
// The value of name will remain
// unchanged because x.name is not nullish
x.name ??= "Shyam";
// There is no any property named age in object x .
// So the value of x.age will be
// undefined and undefined means nullish.
// that's why the value of age will be assigned.
x.age ??= 18;
console.log(x.name) // Ram
console.log(x.age) // 18
HTML
JS Bin
Hello Geeksforgeeks
输出 :
12
13
示例 2:
Javascript
let x = {
name : "Ram"
}
// The value of name will remain
// unchanged because x.name is not nullish
x.name ??= "Shyam";
// There is no any property named age in object x .
// So the value of x.age will be
// undefined and undefined means nullish.
// that's why the value of age will be assigned.
x.age ??= 18;
console.log(x.name) // Ram
console.log(x.age) // 18
输出 :
"Ram"
18
示例 3:
HTML
JS Bin
Hello Geeksforgeeks
输出 :
逻辑无效分配如何工作
让我们讨论一下这个逻辑空赋值运算符是如何工作的。首先我们都知道逻辑空赋值表示为x ??= y ,这是由两个运算符空值合并运算符和赋值运算符符派生的,我们也可以将其写为x ?? (x = y) 。现在 javascript 首先检查x ,如果它为空,则y的值将分配给x 。
支持的浏览器
- 铬 85
- 边缘 85
- 火狐 79
- 野生动物园 14