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

查看:166
本文介绍了是否有“空合并”? 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!';

这是排序ick嘿恕我直言。我可以做得更好吗?

Which is sorta icky IMHO. Can I do better?

推荐答案

C#null合并运算符的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天全站免登陆