什么是空值合并运算符[Nullish coalescing operator](??)?

作者:重庆崽儿Brand

先说结论

当运算符左侧的值为 null 或者 undefined 时,返回运算符右侧的值,否则返回左侧的值

示例如下:

let test = null ?? "not null"
console.log(test) // not null

let test = undefined ?? "not null"
console.log(test) // not null

let test = 0 ?? "not null"
console.log(test) // 0

let test = "" ?? "not null"
console.log(test) // ""

兼容性

问题不大,放心使用

图片描述

怎么发现这个运算符的?

让 ChatGPT 给优化一段代码时,它给出来的 😂 。

有什么用处?

该运算符类似 逻辑或(||)运算符,但是逻辑或可能会遇到一些意外的情况,比如,你需要将""0这些假值视为可用值时,逻辑或就会出问题,使用逻辑或时就需要对 ""0 再做单独的判断。

使用 空值合并运算符(??) 会使代码更加简洁。

**感谢你的阅读 ❤️ **

文章归类于: 学习笔记

文章标签: #Javascript#前端

版权声明: 自由转载-署名-非商用