2

ES11中的空值合并运算符

 2 years ago
source link: https://segmentfault.com/a/1190000040531789
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ES11中的空值合并运算符

发布于 今天 14:25

小编在自己的朋友圈和一些论坛中,都有看到一些前端或者后端被js中判断折磨到起飞,特别是针对空字符串和数字0,在js中,以下6种情况是false

  • undefined
  • false
  • ''或""(特别的,当字符串中间全是空格的时候,会判断为true)

为了解决这个痛点,es11中引入空值合并运算符。使用??运算符之前我们为了兼容性好一些,会写这样的代码

const b = 2
const a = b || 5 // 相当于给a一个默认值
console.log(a)  // 2

如果例子中的b的值为以上会判断为false的情况,上述例子中的值就会出现一些问题,比如

// 实例一
const b = 0
const a = b || 5
console.log(a) // 5

// 实例二
const b = false
const a = b || 5
console.log(a) // 5

// 实例三
const b = ''
const a = b || 5
console.log(a) // 5

针对实际项目中的需求,对于数字0,我们有的时候只是想输出数字0,而不是数字的默认值,es11这个新特性中,只有值是undefined或者null的时候,才使用默认值,就像这样

// 实例一
const b = 2
const a = b ?? 6
console.log(a) // 2

// 实例二
const b = 0
const a = b ?? 6
console.log(a) // 0

// 实例三
const b = false
const a = b ?? 6
console.log(a) // false

// 实例四
const b = undefined
const a = b ?? 6
console.log(a) // 6
// 实例五
const b = null
const a = b ?? 6        
console.log(a) // 6

大家还可以扫描二维码,关注我的微信公众号,蜗牛全栈


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK