Javascript中是否有空合并运算符?

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

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

我可以为Javascript找到的最佳近似是使用条件运算符:

var someString = null;
var whatIWant = someString ? someString : 'Cookies!';

这有点讨厌IMHO。我能做得更好吗?


当前回答

请注意null的JavaScript特定定义。javascript中“无值”有两个定义。1.空:当变量为空时,表示该变量中不包含数据,但该变量已在代码中定义。这样地:

var myEmptyValue = 1;
myEmptyValue = null;
if ( myEmptyValue === null ) { window.alert('it is null'); }
// alerts

在这种情况下,变量的类型实际上是Object。测试它。

window.alert(typeof myEmptyValue); // prints Object

未定义:当一个变量之前没有在代码中定义,并且正如预期的那样,它不包含任何值。这样地:如果(myUndefinedValue==undefined){window.alert('it is undefined');}//警报

如果是这种情况,则变量的类型为“undefined”。

注意,如果您使用类型转换比较运算符(==),JavaScript将对这两个空值起同等作用。要区分它们,请始终使用类型严格比较运算符(==)。

其他回答

是的,它很快就要来了。请参阅此处的提案和此处的实施状态。

它看起来像这样:

x ?? y

实例

const response = {
  settings: {
    nullValue: null,
    height: 400,
    animationDuration: 0,
    headerText: '',
    showSplashScreen: false
  }
};

const undefinedValue = response.settings?.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings?.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings?.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings?.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings?.showSplashScreen ?? true; // result: false

注意,React的create-React-app工具链支持自3.3.0版(发布于5.12.2019)以来的空合并

可选的链接和空合并运算符我们现在支持可选的链接和无效合并运算符!//可选链接一(); // 如果“a”为空/未定义,则为undefinedbc、 //如果“b”为空/未定义,则未定义//空聚结未定义??'其他默认值';//result:'其他默认值'空??'其他默认值';//result:'其他默认值''' ?? '其他默认值';//结果:“”0 ?? 300; // 结果:0假的??真;//结果:false

也就是说,如果你使用create-react-app3.3.0+,你可以开始在你的react应用中使用空联合运算符。

逻辑零赋值,2020+解决方案

当前正在向浏览器中添加新的运算符??=。这将组合空合并运算符??赋值运算符=。

注意:这在公共浏览器版本中尚不常见。将随可用性更改而更新。

??= 检查变量是否未定义或为空,如果已定义则短路。如果没有,则将右侧值分配给变量。

基本示例

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

对象/阵列示例

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

浏览器支持1月22日-89%

Mozilla文档

它有望很快在Javascript中提供,因为截至2020年4月,它处于提案阶段。您可以在此处监视状态以获得兼容性和支持-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

对于使用Typescript的用户,您可以使用Typescript 3.7中的零合并运算符

从文档中-

你可以想到这个功能-??操作员-作为“跌倒”的方式当处理null或undefined时,返回到默认值。当我们编写类似代码让x=foo??bar();这是一种新的说法,即当foo值为“present”时将使用它;但当它为空或未定义时,在其位置计算bar()。

如果||作为C#??的替代品??在您的情况下还不够好,因为它包含空字符串和零,所以您可以始终编写自己的函数:

 function $N(value, ifnull) {
    if (value === null || value === undefined)
      return ifnull;
    return value;
 }

 var whatIWant = $N(someString, 'Cookies!');