ES2020新語法 空值合併運算子

2021-10-11 05:58:30 字數 1951 閱讀 9161

空值合併操作符??)是乙個邏輯操作符,當左側的運算元為null或者undefined時,返回其右側運算元,否則返回左側運算元。

const a =

null??

"default string"

;// "default string"

const b = undefined ??32

;// 32

邏輯或操作符||)不同,邏輯或操作符會在左側運算元為假值時返回右側運算元。

const a =

""||

"default string"

;// "default string"

const b =""?

?"default string"

;// ""

const c =0||

32;// 32

const d =0?

?32;// 0

const e =

false

||"default string"

;// "default string"

const f =

false??

"default string"

;// false

也就是說,空值運算子僅在左側運算元為null或者undefined的時候才返回右側運算元,而邏輯或操作符在左側運算元為nullundefined""0nanfalse的時候都會返回右側運算元。

下面來看一下常見用法:

空值合併運算子把0""nan都視為有效值。僅在第乙個運算元為nullundefined時才返回第二個運算元。

let foo;

// undefined

let somedummytext = foo ?

?'hello!'

;// hello

與 or 和 and 邏輯操作符相似,當左表示式不為nullundefined時,不會對右表示式進行求值。

functiona(

)functionb(

)functionc(

)a()

??c(

)// c方法不會呼叫b(

)??c

()// c方法會被呼叫

下面的**會丟擲syntaxerror,因為空值合併操作符和其他邏輯操作符之間的運算優先順序/運算順序是未定義的。

null

|| undefined ?

?"foo"

;// 丟擲 syntaxerror

true

|| undefined ?

?"foo"

;// 丟擲 syntaxerror

如果使用括號來顯式表明運算優先順序,是沒有問題的:

(

null

|| undefined )??

"foo"

;// 返回 "foo"

空值合併操作符針對undefinednull這兩個值,可選鏈式操作符(?.) 也是如此。

參考:空值合併運算子 - mdn

ES2020的js新特性

1.可選鏈 可選鏈,操作符,在訪問屬性或方法時,若存在為空的中間量,則返回undefined,在長鏈條的屬性訪問時,可節省 const stu const cityname stu.address?city?name cityname undefined const res stu.somemeth...

ES2020的這些新功能令人期待

const user if user user.address if user user.address user.address.prop1 user.address.prop1.prop2 user.address.prop1.prop2.prop3 user.address.prop1.pro...

ES6新語法上

es6新語法 1.變數 賦值var 可以重複定義 不能限制修改 沒有塊級作用域 let 不能重複定義 變數 塊級作用域 const 不能重複定義 常量 塊級元素解構賦值 左右兩邊必須一樣,右邊得是個東西 必須定義和賦值同步完成 2.函式 普通 function 函式,引數 箭頭函式 引數,引數 如果...