?? 空值合并操作符
用法:邏輯操作符,左側為null和undefined時,才傳回右側的值
var name = null
console.log(name ?? '-') // -
var obj = {
name: 'sun'
}
console.log(obj.name ?? '-') // sun
console.log(obj.age ?? '-') // -
?. 可選鍊操作符
可選鍊在JavaScript中是一種簡寫形式
功能類似于‘.’ 鍊式操作符,不同之處在于,在引用為空null 或者 undefined 的情況下不會引起錯誤,該表達式短路傳回值是 undefined
舉個例子:
var personObj = {
sun: {
age: 18
}
}
// 我們正常的調用是
console.log(personObj.sun.age) // 18
但是如果是下面這種情況
var personObj = {}
console.log(personObj.sun) // 傳回undefined
console.log(personObj.sun.age) // 報錯Cannot read property 'age' of undefined
// 因為personObj.sun是undefined,繼續讀取personObj.sun.age會報錯
解決方法:
我們最想想到的可能是if else 判斷或者使用三目運算符
var personObj = {}
console.log(personObj.sun ? personObj.sun.age : '-' ) // -
但是這樣寫不夠簡便,JavaScript就提供了可選鍊
//當寫成 a?.b, 編譯器會自動生成如下代碼
a === null || a === void 0 ? void 0 : a.b
// 備注:undefined這個值在非嚴格模式下會被重新指派,使用void 0必定傳回真正的 undefined
可選鍊’?.'前面的部分是 undefined 或者 null,它會停止運算并傳回該部分
上面我們就可以簡寫為
var personObj = {}
console.log(personObj.sun ?.age) // undefined 不會報錯
注意:personObj 是需要聲明的,不然會報錯
擴充使用 ?.() 和 ?.[]:
?.() 用于調用一個可能不存在的函數
let funObj = {
name() {
console.log('小太陽')
}
}
let funObjNull = {}
funObj.name() ?. () // 小太陽
funObjNull.name ?. () // 不列印
如果我們想使用方括号 [] 而不是點符号 . 來通路對象屬性,文法 ?.[] 也可以使用
let personObj = {
name: 'sun'
};
let personObj2 = null;
let key = 'name';
console.log( personObj?.[key] ); // sun
console.log( personObj2?.[key] ); // undefined
// 和delete一起使用
delete personObj?.name; // 如果 user 存在,則删除 user.name
??配合?.一起使用(當沒資料的時候給個預設值)
var personObj = {
sun: {
age: 18
}
}
console.log(personObj.sun ?. age ?? '-') // 18
console.log(personObj.sun ?.address ?? 'xxx' ) // xxx