??之间的区别 和||

萨沙姆

我正在研究ES2020中提议的新功能,偶然发现了?? 运算符也称为“空位合并运算符”。

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

alex2007v

解释非常简单,假设我们遇到下一种情况,如果对象中存在某个值,则希望获取该值;如果该值未定义或为null,则要使用其他值

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网站文档中找到有关此信息的更多信息

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章