TypeScript 编程,|| 和 ?? 的区别是什么?

||(逻辑或运算符)

  • 作用:如果左侧操作数为"假值"(falsy),返回右侧操作数。
  • 假值(falsy)的定义:
    • false
    • 0
    • ''(空字符串)
    • null
    • undefined
    • NaN

示例:

typescript 复制代码
const a = 0 || 'default'; // 'default'
const b = false || 'default'; // 'default'
const c = '' || 'default'; // 'default'
const d = null || 'default'; // 'default'
const e = undefined || 'default'; // 'default'

const f = 'value' || 'default'; // 'value'
const g = 42 || 'default'; // 42

??(空值合并运算符)

  • 作用:如果左侧操作数为 nullundefined(其它假值除外),返回右侧操作数。

示例:

typescript 复制代码
const a = 0 ?? 'default'; // 0
const b = false ?? 'default'; // false
const c = '' ?? 'default'; // ''
const d = null ?? 'default'; // 'default'
const e = undefined ?? 'default'; // 'default'

const f = 'value' ?? 'default'; // 'value'
const g = 42 ?? 'default'; // 42

注意,?? 的优先级比 || 高。

相关推荐
人工智能训练师4 分钟前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny078 分钟前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy1 小时前
css的基本知识
前端·css
昔人'1 小时前
css `lh`单位
前端·css
Nan_Shu_6143 小时前
Web前端面试题(2)
前端
知识分享小能手3 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队4 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光4 小时前
css之一个元素可以同时应用多个动画效果
前端·css
huangql5204 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
Days20505 小时前
LeaferJS好用的 Canvas 引擎
前端·开源