本文共 1267 字,大约阅读时间需要 4 分钟。
A new JavaScript feature that’s going to be widely used, soon, is the nullish coalescing operator ??
.
即将被广泛使用的新JavaScript功能是无效的合并运算符??
。
What’s that? ??
?
那是什么? ??
?
Have you ever used ||
to set a default value if a variable was null or undefined?
您曾经使用过||
如果变量为null或未定义,设置默认值吗?
For example, like this:
例如,像这样:
const myColor = color || 'red'
Well, nullish coalescing is going to replace ||
in there:
好吧,无效的合并将替换||
在那里:
const myColor = color ?? 'red'
Why?
为什么?
Well, there is a whole range of bugs that hide underneath the surface when using ||
to provide a fallback value.
好吧,当使用||
时,有很多错误隐藏在表面之下。 提供后备值。
In short, ||
handles values as falsy. ??
handles values as nullish (hence the name).
简而言之, ||
将值视为虚假。 ??
将值处理为空值(因此命名)。
Which means that with ||
the second operand is evaluated if the first operand is undefined
, null
, false
, 0
, NaN
or ''
.
这意味着||
如果第一个操作数是undefined
, null
, false
, 0
, NaN
或''
,则计算第二个操作数。
??
on the other hand limits this list to only undefined
and null
.
??
另一方面,将此列表限制为只有undefined
和null
。
Which might suit your use case better!
哪个可能更适合您的用例!
The blog has a much more detailed post on this operator, but you got the gist here.
博客上有关于此运算符的更详细的文章,但是您在这里找到了要点。
It’s currently available in Chrome Canary, and in !
目前可在Chrome Canary和 !
Check my
查看我的
翻译自:
转载地址:http://qqqgb.baihongyu.com/