javascript 便签

发布时间 2024-01-09 17:12:04作者: PKGAME

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

  参考至: 这里