相关的是有一个“空合并”运营商在JavaScript中?- JavaScript 现在有一个??运算符,我发现它使用得更频繁。以前大多数 JavaScript 代码使用||.
let userAge = null
// These values will be the same.
let age1 = userAge || 21
let age2 = userAge ?? 21
Run Code Online (Sandbox Code Playgroud)
在什么情况下会??和||行为不同?
ES2020 introduced the nullish coalescing operator (??) which returns the right operand if the left operand is null or undefined. This functionality is similar to the logical OR operator (||). For example, the below expressions return the same results.
const a = undefined
const b = "B"
const orOperator = a || b
const nullishOperator = a ?? b
console.log({ orOperator, nullishOperator })
Run Code Online (Sandbox Code Playgroud)
result:
{
orOperator:"B",
nullishOperator:"B"
}
Run Code Online (Sandbox Code Playgroud)
So how is the nullish operator different …