我正在访问MDN关于逻辑零赋值的文章。MDN提供的等价版本是x ?? (x = y)
,这还不够清楚,需要进一步挖掘。
这个代码是吗
let x = null;
x ??= 12;
相当于:
let x = null;
if (x === null || x === undefined) {
x = 12;
}
是的,它只在x
为null时赋值。
x ?? (x = y)
或
if (x === null || x === undefined) {
x = 12;
}
它NOT相当于
x = x ?? y
存在差异,您可以使用const
而不是let
来验证这一点。这样,重新分配将导致错误。这也适用于其他逻辑赋值,如AND(&&=
(和OR(||=
(赋值运算符。
// no const reassignment error here
// because a || (a = 'updated') doesn't evaluate the second expression
// if it was a = a || 'updated', it would throw an error
const a = 'initial'
a ||= 'updated'
console.log(a)
const b = null
b &&= 'updated'
console.log(b)
const c = 'initial'
c ??= 'updated' // c ?? (c
console.log(c)
// The below 3 examples will evaluate the second expression
// and const reassignment error is thrown
try {
const d = null
d ||= 'updated'
} catch (e) {
console.log("|| Error: " + e.message)
}
try {
const e = 'initial'
e &&= 'updated'
} catch (e) {
console.log("&& Error: " + e.message)
}
try {
const f = null
f ??= 'updated'
} catch (e) {
console.log("?? Error: " + e.message)
}
逻辑零赋值(x??=y(运算符仅在x为零(null或未定义(时赋值