空合并运算符(??)与ECMAScript中的逻辑OR运算符()有何不同?
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 })
result:
{
orOperator:"B",
nullishOperator:"B"
}
So how is the nullish operator different and what is its use case?
回答
本||-运算符的计算结果为右手边当且仅当左手边是一个falsy值。
-??运算符(空合并)当且仅当左侧为null或时才对右侧求值undefined。
false, 0, NaN, ""(空字符串) 例如被认为是假的,但也许你真的想要这些值。在这种情况下,??-operator 是正确的操作符。
THE END
二维码