【问题标题】:Difference between ?? and ||之间的区别??和 ||
【发布时间】:2020-05-10 11:57:13
【问题描述】:

我正在浏览 ES2020 中提出的新功能,我偶然发现了 ??运算符也称为“空值合并运算符”。

解释很模糊,我仍然不明白它与逻辑 OR 运算符有何不同 (||)

【问题讨论】:

标签: javascript ecmascript-2020


【解决方案1】:

解释很简单让我们假设我们有下一种情况,如果它存在于对象中,我们想要获取一个值,或者如果它是未定义或为空的,则使用其他值

const obj = { a: 0 }; 
const a = obj.a || 10; // gives us 10

// if we will use ?? operator situation will be different
const obj = { a: 0 };
const a = obj.a ?? 10; // gives us 0

// you can achieve this using this way
const obj = { a: 0 };
const a = obj.a === undefined ? 10 : obj.a; // gives us 0

// it also work in case of null
const obj = { a: 0, b: null };
const b = obj.b ?? 10; // gives us 10

基本上这个操作符接下来会做:

// I assume that we have value and different_value variables
const a = (value === null || value === undefined) ? different_value : value;

您可以在MDN web docs找到更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 2014-09-20
    • 2010-10-28
    • 2015-10-04
    • 2012-08-12
    • 2011-02-18
    • 2019-12-21
    • 2018-01-18
    相关资源
    最近更新 更多