空值合并操作符(??)
只有當(dāng)左側(cè)為null和undefined時师郑,才會返回右側(cè)的數(shù)
????????空值合并操作符(??)是一個邏輯操作符,當(dāng)左側(cè)的操作數(shù)為null或者undefined時漫蛔,返回其右側(cè)操作數(shù)嗜愈,否則返回左側(cè)操作數(shù)。
????????與邏輯或操作符(||)不同莽龟,邏輯或操作符會在左側(cè)操作數(shù)為假值時返回右側(cè)操作數(shù)蠕嫁。也就是說,如果使用||來為某些變量設(shè)置默認(rèn)值毯盈,可能會遇到意料之外的行為剃毒。比如為假值(例如,''或0)時搂赋。見下面的例子赘阀。
const foo =null? ??? 'default string';
console.log(foo);????????// expected output: "default string"const baz = 0 ?? 42;
console.log(baz);????????// expected output: 0
const nullValue =? null;
const emptyText = "";????????// 空字符串,是一個假值脑奠,Boolean("")? ===? falseconst someNumber = 42;
const valA = nullValue ?? "valA 的默認(rèn)值";
const valB = emptyText ?? "valB 的默認(rèn)值";
const valC = someNumber ?? 0;
console.log(valA); ????????//? "valA 的默認(rèn)值"
console.log(valB);????????//? ""(空字符串雖然是假值纤壁,但不是 null 或者 undefined)
console.log(valC);????????//? 42
可選鏈操作符(?.)
????????可選鏈操作符(?.)允許讀取位于連接對象鏈深處的屬性的值,而不必明確驗(yàn)證鏈中的每個引用是否有效捺信。
?????????.操作符的功能類似于.鏈?zhǔn)讲僮鞣妹剑煌幵谟冢谝脼榭?nullish)?(null或者undefined) 的情況下不會引起錯誤迄靠,該表達(dá)式短路返回值秒咨。
const adventurer = {
? name: 'Alice',
? cat: {
? ? name: 'Dinah'?
????}
};
const dogName = adventurer.dog?.name;
console.log(dogName);????????// expected output: undefined
console.log(adventurer.someNonExistentMethod?.());????????// expected output: undefined
語法:obj?.prop ???? obj?.[expr]????????arr?.[index]????????func?.(args)
函數(shù)調(diào)用:
let result = someInterface.customMethod?.();
如果希望允許 someInterface 也為 null或者 undefined ,那么你需要像這樣寫 someInterface?.customMethod?.()
可選鏈與表達(dá)式:
let nestedProp = obj?.['prop' + 'Name'];
可選鏈訪問數(shù)組:
let arrayItem = arr?.[42];
例子:
? ? let myMap =new Map();
? ? myMap.set("foo", {name: "baz", desc: "inga"});
? ? let nameBar = myMap.get("bar")?.name;
? ? 在一個不含 bar 成員的 Map 中查找 bar 成員的 name 屬性掌挚,因此結(jié)果是 undefined雨席。
短路計(jì)算:
let potentiallyNullObj =null;
let x = 0;
let prop = potentiallyNullObj?.[x++];
console.log(x); // x 將不會被遞增,依舊輸出 0當(dāng)在表達(dá)式中使用可選鏈時吠式,如果左操作數(shù)是 null或 undefined陡厘,表達(dá)式將不會被計(jì)算
連用可選鏈操作:
let customer = {
? name: "Carl",
? details: {
? ? age: 82,
? ? location: "Paradise Falls"http:// details 的 address 屬性未有定義? }
};
let customerCity = customer.details?.address?.city;????
// … 可選鏈也可以和函數(shù)調(diào)用一起使用
let duration = vacations.trip?.getTime?.();
空值合并操作符可以在使用可選鏈時設(shè)置一個默認(rèn)值:
let customer = {
? name: "Carl",
? details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity);? // “暗之城”