?.
?.
操作符或可選的鏈?zhǔn)竭\(yùn)算符是一個(gè)很有用的運(yùn)算符炒辉,用于檢查一個(gè)值是否已經(jīng)被設(shè)置,當(dāng)它被設(shè)置后再繼續(xù)。
if(data && data.subdata && data.subdata.name === "cool") {
console.log("hi")
}
// 鏈?zhǔn)脚袛嗝總€(gè)屬性存在性
if(data?.subdata?.name === "cool") {
console.log("hi")
}
??
??
操作符是一個(gè)檢查一條語(yǔ)句左值是否為空的操作符拥峦,如果為真烤蜕,它將返回右邊的值幢踏。
const x = null ?? 'string';
// x: "string"
const y = 12 ?? 42;
// y: 12
??=
邏輯空賦值運(yùn)算符 (x ??= y
) 僅在 x
是 (null
或 undefined
) 時(shí)對(duì)其賦值。
const a = { duration: 50 };
a.duration ??= 10;
console.log(a.duration);
// a.duration: 50
a.speed ??= 25;
console.log(a.speed);
// a.speed: 25