JavaScript中是否有“null coalescing”运算符?

1562

JavaScript 中是否有空值合并运算符(null coalescing operator)?

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

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

我认为在JavaScript中最好的逼近方法是使用条件运算符:

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

我认为那有点恶心。我能做得更好吗?


39
2018年的注释:x ?? y 语法现在处于一阶段提案状态 - 空值合并 - Aprillion
4
现在有一个Babel插件,可以使用这个确切的语法。 - Jonathan Sudiaman
11
2019年的注释:现在处于第三阶段状态! - Daniel Schaffer
2
2019年后期的注释:空值合并运算符在TypeScript 3.7中可用! - Daniel Schaffer
5
2020年1月的说明:空值合并运算符(nulish coalescing operator)已经可以在Firefox 72中原生支持,但是可选链操作符(optional chaining operator)仍未支持。 - Kir Kanos
6
空值合并运算符(x ?? y)和可选链式操作符(user.address?.street)现在都达到了第四阶段。这意味着什么呢?请看这篇文章的详细描述:https://2ality.com/2015/11/tc39-process.html#stage-4%3A-finished 。 - Mass Dot Net
19个回答

4

这里有两个项目:

  1. 逻辑或

const foo = '' || '默认字符串';

console.log(foo); // 输出结果是 '默认字符串'

  1. 空值合并运算符

const foo = '' ?? '默认字符串';

console.log(foo); // 输出结果是空字符串,即 ''

空值合并运算符 (??) 是一种逻辑运算符,当其左侧操作数为 null 或 undefined 时,返回其右侧操作数,否则返回其左侧操作数。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator


1
在操作符发布之前,这次的讨论是必要的。但是由于你的回答只比@faithful的回答差,而且时间晚得多,我认为你说得太多了。 - Gerard ONeill

4
请注意,React的create-react-app工具链支持空值合并自从版本3.3.0(发布于2019年5月12日)。从发布说明中可以看到:

Optional Chaining and Nullish Coalescing Operators

We now support the optional chaining and nullish coalescing operators!

// Optional chaining
a?.(); // undefined if `a` is null/undefined
b?.c; // undefined if `b` is null/undefined

// Nullish coalescing
undefined ?? 'some other default'; // result: 'some other default'
null ?? 'some other default'; // result: 'some other default'
'' ?? 'some other default'; // result: ''
0 ?? 300; // result: 0
false ?? true; // result: false

如果您使用的是create-react-app 3.3.0+,那么您可以开始在React应用程序中使用空值合并运算符。


2
希望很快能够在JavaScript中使用,截至2020年4月,它仍处于提案阶段。您可以在此处监视其兼容性和支持情况-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator 对于使用Typescript的人,您可以使用来自Typescript 3.7nullish coalescing operator 从文档中 -
你可以把这个功能——?? 运算符——看作是一种处理 nullundefined 时回退到默认值的方式。当我们编写如下代码时:let x = foo ?? bar();,这是一种新的表达方式,意味着当值 foo 存在时将使用它;但当它为 nullundefined 时,计算并使用 bar() 的返回值代替。

1

ECMAScript 2021引入了两个新功能:

  1. Nullish coalescing operator (??)是一个逻辑运算符,当左侧操作数为null或undefined时返回右侧操作数,否则返回左侧操作数。

let b = undefined ?? 5;

console.log(b); // 5

  1. 逻辑空值赋值 (x ??= y) 运算符只在 x 为 null 或 undefined 时进行赋值。

const car = {speed : 20};
car.speed ??= 5;
console.log(car.speed);
car.name ??= "reno";
console.log(car.name);

关于逻辑空赋值的更多信息可以在这里找到 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment

关于空值合并运算符的更多信息可以在这里找到 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator


1
需要支持旧浏览器并具有对象层次结构。
body.head.eyes[0]  //body, head, eyes  may be null 

可以使用这个代码。

(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'

0
现在最新版本的主要浏览器(如Chrome、Edge、Firefox、Safari等)已经完全支持该功能。下面是空操作符和Nullish Coalescing操作符之间的比较。
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

0

使用Babel的人需要升级到最新版本才能使用nullish coalescing(??):

Babel 7.8.0默认支持新的ECMAScript 2020功能:您不再需要使用preset-env为nullish coalescing(??),optional chaining(?.)和dynamic import()启用单独的插件。

来自https://babeljs.io/blog/2020/01/11/7.8.0


0

链式多值 / 多个值

  • 启用“短路”:如果第一个值有效,则不再评估任何其他值
  • 这意味着顺序很重要,最左边的值优先考虑
const value = first ?? second ?? third ?? "default";

-1
我试图检查输入是否为空,然后相应地使用该值。这是我的代码。
let valueToBeConsidered = !inputValue ? "trueCondition" : "falseCondition",

所以如果inputValue为null,则valueToBeConsidered = falseCondition,如果inputValue有值,则valueToBeConsidered = trueCondition


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接