gpt4 book ai didi

Javascript逻辑空赋值等价

转载 作者:行者123 更新时间:2023-12-04 14:55:17 26 4
gpt4 key购买 nike

我正在访问 MDN article for Logical Nullish Assignment . MDN 提供的等效版本是 x ?? (x = y)这还不够清楚,需要深入挖掘。
这段代码是:

let x = null;

x ??= 12;
相当于:
let x = null;

if (x === null || x === undefined) {
x = 12;
}

最佳答案

是的,它只分配 x是无效的。

x ?? (x = y)
或者
if (x === null || x === undefined) {
x = 12;
}
不是 相当于
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)
}

关于Javascript逻辑空赋值等价,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68173744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com