let x = foo ?? bar();
等价于下面
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
是用来解决以前的类似问题:
function initializeAudio() {
let volume = localStorage.volume || 0.5
// ...
}
When localStorage.volume is set to 0, the page will set the volume to 0.5 which is unintended. ?? avoids some unintended behavior from 0, NaN and "" being treated as falsy values.
完整参考: https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#nullish-coalescing
网友评论