是否存在“空合并”? JavaScript 中的运算符?
JavaScript 中有空合并运算符吗?
例如,在 C# 中,我可以这样做:
String someString = null;
var whatIWant = someString ?? "Cookies!";
我能想到的 Javascript 的最佳近似是使用条件运算符:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
恕我直言,这有点令人讨厌。 我可以做得更好吗?
Is there a null coalescing operator in Javascript?
For example, in C#, I can do this:
String someString = null;
var whatIWant = someString ?? "Cookies!";
The best approximation I can figure out for Javascript is using the conditional operator:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
Which is sorta icky IMHO. Can I do better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
更新
JavaScript 现在支持 nullish合并运算符 (??)。 当其左侧操作数为
null
或undefined
时,它返回其右侧操作数,否则返回其左侧操作数。旧答案
使用前请检查兼容性。
JavaScript 中 C# 空合并运算符 (
??
) 的等效项是使用逻辑 OR (||
):在某些情况下(如下所述)该行为不会与 C# 的方式相匹配,但这是在 JavaScript 中分配默认/替代值的通用、简洁的方式。
说明
无论第一个操作数的类型如何,如果将其转换为布尔值会导致
false
,则赋值操作将使用第二个操作数。 请注意以下所有情况:这意味着:
Update
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is
null
orundefined
, and otherwise returns its left-hand-side operand.Old Answer
Please check compatibility before using it.
The JavaScript equivalent of the C# null coalescing operator (
??
) is using a logical OR (||
):There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
Clarification
Regardless of the type of the first operand, if casting it to a Boolean results in
false
, the assignment will use the second operand. Beware of all the cases below:This means:
该解决方案的工作原理类似于 SQL 合并函数,它接受任意数量的参数,如果它们都没有值,则返回 null。 它的行为类似于 C# ?? 运算符的含义是“”、false 和 0 被视为 NOT NULL,因此算作实际值。 如果您有 .net 背景,这将是最自然的感觉解决方案。
this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.
是的,它即将到来。 请参阅此处的提案和此处的实施状态。
它看起来像这样:
示例
Yes, it is coming soon. See proposal here and implementation status here.
It looks like this:
Example
如果
||
作为 C# 的??
的替代品在您的情况下不够好,因为它会吞下空字符串和零,您始终可以编写自己的函数:If
||
as a replacement of C#'s??
isn't good enough in your case, because it swallows empty strings and zeros, you can always write your own function:这里没有人提到 NaN 的潜力,对我来说,它也是一个空值。 所以,我想我应该加两分钱。
对于给定的代码:
如果您要使用
||
运算符,您将获得第一个非 false 值:如果您使用新的
??
(空合并)运算符,您将得到c
,其值为:NaN
这两个对我来说都不合适。 在我自己的合并逻辑小世界中(可能与您的世界不同),我认为 undefined、null 和 NaN 都是“null-ish”。 因此,我希望从合并方法中返回 d(零)。
如果有人的大脑像我一样工作,并且您想排除
NaN
,那么这个自定义coalesce
方法(与 这里发布的)将实现这一点:对于那些希望代码尽可能短并且不介意有点不够清晰的人,您也可以按照@impinball的建议使用它。 这利用了 NaN 永远不等于 NaN 的事实。 您可以在这里阅读更多相关内容:为什么 NaN 不等于 NaN?< /a>
Nobody has mentioned in here the potential for
NaN
, which--to me--is also a null-ish value. So, I thought I'd add my two-cents.For the given code:
If you were to use the
||
operator, you get the first non-false value:If you use the new
??
(null coalescing) operator, you will getc
, which has the value:NaN
Neither of these seem right to me. In my own little world of coalesce logic, which may differ from your world, I consider undefined, null, and NaN as all being "null-ish". So, I would expect to get back
d
(zero) from the coalesce method.If anyone's brain works like mine, and you want to exclude
NaN
, then this customcoalesce
method (unlike the one posted here) will accomplish that:For those who want the code as short as possible, and don't mind a little lack of clarity, you can also use this as suggested by @impinball. This takes advantage of the fact that NaN is never equal to NaN. You can read up more on that here: Why is NaN not equal to NaN?
??
vs||
vs&&
其他答案都没有比较所有这三个。 由于贾斯汀·约翰逊的评论有这么多票,并且因为 双问号 vs && 在 javascript 中被标记为与此重复,因此在答案中包含
&&
是有意义的。首先,受 Justin Johnson 评论的启发:
||
返回第一个“truey”值,否则返回最后一个值。&&
返回第一个“falsey”值,否则返回最后一个值。??
返回第一个非空、非未定义的值,否则返回最后一个值,无论它是什么。然后,用实时代码演示:
??
vs||
vs&&
None of the other answers compares all three of these. Since Justin Johnson's comment has so many votes, and since double question mark vs && in javascript was marked a duplicate of this one, it makes sense to include
&&
in an answer.First in words, inspired by Justin Johnson's comment:
||
returns the first "truey" value, else the last value whatever it is.&&
returns the first "falsey" value, else the last value whatever it is.??
returns the first non-null, non-undefined value, else the last value, whatever it is.Then, demonstrated in live code:
逻辑空赋值,2020+ 解决方案
当前正在向浏览器添加新的运算符
??=
。 这将空合并运算符??
与赋值运算符=
组合在一起。??=
检查变量是否未定义或为 null,如果已定义则短路。 如果不是,则将右侧值分配给该变量。基本示例
对象/数组示例
浏览器支持 Jan '22 - 89%
Mozilla 文档
Logical nullish assignment, 2020+ solution
A new operator is currently being added to the browsers,
??=
. This combines the null coalescing operator??
with the assignment operator=
.??=
checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.Basic Examples
Object/Array Examples
Browser Support Jan '22 - 89%
Mozilla Documentation
是的,其提案是现在进入第 4 阶段。 这意味着该提案已准备好纳入正式的 ECMAScript 标准。 您已经可以在最新的桌面版 Chrome、Edge 和 Firefox 中使用它,但我们还需要等待一段时间才能实现该功能的跨浏览器稳定性。
看一下下面的示例来演示其行为:
前面的示例相当于:
请注意,无效合并将不会威胁虚假值,就像
||
运算符所做的那样(它只检查< code>undefined 或null
值),因此以下代码片段将如下所示:对于 TypesScript 用户,从 TypeScript 3.7 开始,这个功能现在也可用了。
Yes, and its proposal is Stage 4 now. This means that the proposal is ready for inclusion in the formal ECMAScript standard. You can already use it in recent desktop versions of Chrome, Edge and Firefox, but we will have to wait for a bit longer until this feature reaches cross-browser stability.
Have a look at the following example to demonstrate its behavior:
Previous example is equivalent to:
Note that nullish coalescing will not threat falsy values the way the
||
operator did (it only checks forundefined
ornull
values), hence the following snippet will act as follows:For TypesScript users, starting off TypeScript 3.7, this feature is also available now.
阅读您的说明后,@Ates Goral 的答案提供了如何在 JavaScript 中执行您在 C# 中执行的相同操作。
@Gumbo 的答案提供了检查 null 的最佳方法; 但是,请务必注意 JavaScript 中
==
与===
的区别,尤其是在检查问题时未定义
和/或null
。此处有一篇非常好的文章介绍了两个术语的区别。 基本上,如果您使用
==
而不是===
,JavaScript 将尝试合并您正在比较的值并返回比较结果在合并之后。After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in
==
versus===
in JavaScript especially when it comes to issues of checking forundefined
and/ornull
.There's a really good article about the difference in two terms here. Basically, understand that if you use
==
instead of===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.请注意 JavaScript 中 null 的特定定义。 javascript 中“无值”有两种定义。
1. Null:当一个变量为null时,意味着它不包含任何数据,但是该变量已经在代码中定义了。 像这样:
在这种情况下,变量的类型实际上是 Object。 测试一下。
未定义:当变量之前没有在代码中定义时,并且正如预期的那样,它不包含任何值。 像这样:
如果是这种情况,变量的类型是“未定义”。
请注意,如果您使用类型转换比较运算符 (==),JavaScript 将对这两个空值执行相同的操作。 为了区分它们,请始终使用类型严格的比较运算符 (===)。
beware of the JavaScript specific definition of null. there are two definitions for "no value" in javascript.
1. Null: when a variable is null, it means it contains no data in it, but the variable is already defined in the code. like this:
in such case, the type of your variable is actually Object. test it.
Undefined: when a variable has not been defined before in the code, and as expected, it does not contain any value. like this:
if such case, the type of your variable is 'undefined'.
notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).
这里有两项:
const foo = '' || '默认字符串';
控制台.log(foo); // 输出为“默认字符串”
const foo = '' ?? '默认字符串';
控制台.log(foo); // 输出为空字符串,即 ''
空值合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为 null 或未定义时,它返回其右侧操作数,否则返回其左侧操作数。
https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
There are two items here:
const foo = '' || 'default string';
console.log(foo); // output is 'default string'
const foo = '' ?? 'default string';
console.log(foo); // output is empty string i.e. ''
The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
请注意,React 的
create-react-app
工具链自 版本 3.3.0(2019 年 12 月 5 日发布)。 从发行说明来看:也就是说,如果您使用
create-react-app
3.3.0+,您现在就可以开始在 React 应用程序中使用 null-coalesce 运算符。Note that React's
create-react-app
tool-chain supports the null-coalescing since version 3.3.0 (released 5.12.2019). From the release notes:This said, in case you use
create-react-app
3.3.0+ you can start using the null-coalesce operator already today in your React apps.它有望很快在 Javascript 中推出,因为截至 2020 年 4 月它正处于提案阶段。您可以在此处监控兼容性和支持的状态 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
对于使用 Typescript 的人,可以使用 空值合并运算符 来自 Typescript 3.7
来自文档 -
It will hopefully be available soon in Javascript, as it is in proposal phase as of Apr, 2020. You can monitor the status here for compatibility and support - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
For people using Typescript, you can use the nullish coalescing operator from Typescript 3.7
From the docs -
需要支持旧浏览器并且有对象层次结构
可以使用这个,
Need to support old browser and have a object hierarchy
may use this,
ECMAScript 2021 启用了两个新功能:
有关逻辑空值赋值的更多信息,请参阅https:// /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
有关 Nullish 合并运算符的更多信息可以在此处找到
https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
ECMAScript 2021 enabled two new features:
More about Logical nullish assignment can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment
More about Nullish coalescing operator can be found here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
现在它在 Chrome、Edge、Firefox、Safari 等主流浏览器的最新版本中得到了全面支持。以下是 null 运算符和 Nullish Coalescing 运算符之间的比较
Now it has full support in latest version of major browsers like Chrome, Edge, Firefox , Safari etc. Here's the comparison between the null operator and Nullish Coalescing Operator
使用 Babel 的用户需要升级到最新版本才能使用空值合并(??):
https ://babeljs.io/blog/2020/01/11/7.8.0
Those who are using Babel, need to upgrade to the latest version to use nullish coalescing (??):
From https://babeljs.io/blog/2020/01/11/7.8.0
启用链式多个值/多个值
Chain multiple values / several values
我试图检查输入是否为空,然后相应地使用该值。 这是我的代码。
因此,如果 inputValue 为 null,则 valueToBeConsidered = falseCondition,如果 inputValue 有值,则 valueToBeConsidered = trueCondition
I was trying to check if an input is null and then use the value accordingly. This is my code.
So if inputValue is null then valueToBeConsidered = falseCondition and if inputValue has a value then valueToBeConsidered = trueCondition