Javascript中是否有空合并运算符?
例如,在C#中,我可以这样做:
String someString = null;
var whatIWant = someString ?? "Cookies!";
我可以为Javascript找到的最佳近似是使用条件运算符:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
这有点讨厌IMHO。我能做得更好吗?
Javascript中是否有空合并运算符?
例如,在C#中,我可以这样做:
String someString = null;
var whatIWant = someString ?? "Cookies!";
我可以为Javascript找到的最佳近似是使用条件运算符:
var someString = null;
var whatIWant = someString ? someString : 'Cookies!';
这有点讨厌IMHO。我能做得更好吗?
当前回答
需要支持旧浏览器并具有对象层次结构
body.head.eyes[0] //body, head, eyes may be null
可以使用此,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
其他回答
在阅读了您的澄清之后,@Ates Goral的回答提供了如何在JavaScript中执行您在C#中执行的相同操作。
@Gumbo的答案提供了检查空值的最佳方法;然而,注意JavaScript中==与==的区别很重要,特别是在检查未定义和/或null时。
这里有一篇关于两个术语的区别的非常好的文章。基本上,请理解如果使用==而不是==,JavaScript将尝试合并正在比较的值,并在合并后返回比较结果。
逻辑零赋值,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文档
使用Babel的用户需要升级到最新版本才能使用零合并(??):
Babel 7.8.0默认支持新的ECMAScript 2020功能:不需要启用单独的插件来进行无效合并(??),可选的链接(?.)和动态导入()不再带有预设env
从…起https://babeljs.io/blog/2020/01/11/7.8.0
现在,它在Chrome、Edge、Firefox、Safari等主流浏览器的最新版本中得到了完全支持。下面是空运算符和空合并运算符的比较
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
/* OR Operator */
const undefinedValue = response.settings.undefinedValue || 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue || 'Default Value'; // 'Default Value'
const headerText = response.settings.headerText || 'Hello, world!'; // 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // 300
const showSplashScreen = response.settings.showSplashScreen || true; // true
/* Nullish Coalescing Operator */
const undefinedValue = response.settings.undefinedValue ?? 'Default Value'; // 'Default Value'
const nullValue = response.settings.nullValue ?? ''Default Value'; // 'Default Value'
const headerText = response.settings.headerText ?? 'Hello, world!'; // ''
const animationDuration = response.settings.animationDuration ?? 300; // 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // false
链接多个值/多个值
启用“短路”:如果第一个值之一有效,则不进行任何进一步评估这意味着顺序很重要,最左边的值优先
const value = first ?? second ?? third ?? "default";