js中??和?.的意思
空值合並操作符(??
)
只有當左側為null和undefined時,才會返回右側的數
空值合並操作符(??
)是一個邏輯操作符,當左側的操作數為 null
或者 undefined
時,返回其右側操作數,否則返回左側操作數。
與邏輯或操作符(||
)不同,邏輯或操作符會在左側操作數為假值時返回右側操作數。也就是說,如果使用 ||
來為某些變量設置默認值,可能會遇到意料之外的行為。比如為假值(例如,''
或 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("") === false const someNumber = 42; const valA = nullValue ?? "valA 的默認值"; const valB = emptyText ?? "valB 的默認值"; const valC = someNumber ?? 0; console.log(valA); // "valA 的默認值" console.log(valB); // ""(空字符串雖然是假值,但不是 null 或者 undefined) console.log(valC); // 42
可選鏈操作符( ?.
)
可選鏈操作符( ?.
)允許讀取位於連接對象鏈深處的屬性的值,而不必明確驗證鏈中的每個引用是否有效。?.
操作符的功能類似於 .
鏈式操作符,不同之處在於,在引用為空(nullish ) (null
或者 undefined
) 的情況下不會引起錯誤,該表達式短路返回值
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)
函數調用:
let result = someInterface.customMethod?.(); 如果希望允許 someInterface 也為 null 或者 undefined ,那么你需要像這樣寫 someInterface?.customMethod?.()
可選鏈與表達式: let nestedProp = obj?.['prop' + 'Name'];
可選鏈訪問數組: 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 屬性,因此結果是 undefined。
短路計算: let potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; console.log(x); // x 將不會被遞增,依舊輸出 0 當在表達式中使用可選鏈時,如果左操作數是 null 或 undefined,表達式將不會被計算
連用可選鏈操作: let customer = { name: "Carl", details: { age: 82, location: "Paradise Falls" // details 的 address 屬性未有定義 } }; let customerCity = customer.details?.address?.city; // … 可選鏈也可以和函數調用一起使用 let duration = vacations.trip?.getTime?.();
空值合並操作符可以在使用可選鏈時設置一個默認值: let customer = { name: "Carl", details: { age: 82 } }; let customerCity = customer?.city ?? "暗之城"; console.log(customerCity); // “暗之城”