javascript 便签

1. es6 新语法

  ??:空值合并操作符

  空值合并操作符( ?? )是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。 空值合并操作符( ?? )与逻辑或操作符( || )不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。

复制代码
 1 const a = null
 2 undefined
 3 const b = undefined
 4 undefined
 5 const c = ''
 6 undefined
 7 const d = 12
 8 undefined
 9 const e = '33'
10 undefined
11 a ?? 1
12 1
13 b ?? 1
14 1
15 c ?? 1
16 ''
17 d ?? 1
18 12
19 e ?? 1
20 '33'
复制代码

   ?.:可选链操作符

    可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。( ?. ) 操作符的功能类似于( . )链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函    

    数调用一起使用时,如果给定的函数不存在,则返回 undefined。

复制代码
a?.b
// 等同于
a == null ? undefined : a.b
a?.[x]
// 等同于
a == null ? undefined : a[x]
a?.b()
// 等同于
a == null ? undefined : a.b()
a?.()
// 等同于
a == null ? undefined : a()
复制代码

  ??=:空值运算符

    逻辑空赋值运算符 (x ??= y) 仅在 x 是 null 或 undefined 时对其赋值。

复制代码
 1 let x = undefined
 2 undefined
 3 x ??= 1
 4 1
 5 x
 6 1
 7 let x = null
 8 undefined
 9 x ??= 1
10 1
11 x
12 1
13 x = 12
14 12
15 x ??= 1
16 12
17 x
18 12
复制代码

  参考至: 这里

 

 

posted @   PKGAME  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示