是否存在“空合并"?JavaScript 中的运算符? [英] Is there a "null coalescing" operator in JavaScript?

查看:33
本文介绍了是否存在“空合并"?JavaScript 中的运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Javascript 中有空合并运算符吗?

Is there a null coalescing operator in Javascript?

例如,在 C# 中,我可以这样做:

For example, in C#, I can do this:

String someString = null;
var whatIWant = someString ?? "Cookies!";

我能找出的 Javascript 的最佳近似值是使用条件运算符:

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?

推荐答案

更新

JavaScript 现在支持 空合并运算符 (??).当其左侧操作数为 nullundefined 时,它返回其右侧操作数,否则返回其左侧操作数.

JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.

请在使用前检查兼容性.

Please check compatibility before using it.

与 C# 空合并运算符 (??) 等效的 JavaScript 使用逻辑 OR (||):

The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var whatIWant = someString || "Cookies!";

在某些情况下(在下面澄清),行为与 C# 的行为不匹配,但这是在 JavaScript 中分配默认值/替代值的通用、简洁的方式.

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.

无论第一个操作数的类型如何,如果将其转换为布尔值导致 false,则赋值将使用第二个操作数.请注意以下所有情况:

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:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

这意味着:

var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"

这篇关于是否存在“空合并"?JavaScript 中的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆