一、 ?.
可选链操作符(?.)允许读取位于连接对象链深处的属性值,而不必明确验证链中的每个引用是否有效。
let nestedProp = obj.first && obj.first.second; // 等价于 let nestedProp = obj.first?.second;
js会在尝试访问obj.first.second
之前隐式的检查并确定obj.first
既不是null
也不是undefined
。如果obj.first
是null
或者undefined
,表达式将会短路计算直接返回undefined
二、??
空值合并操作符,可以在使用可选链时设置一个默认值
let customer = { name: "Carl", details: { age: 82 } }; let customerCity = customer?.city ?? "暗之城"; console.log(customerCity); // “暗之城” 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
三、语法
obj?.prop obj?.[expr] arr?.[index] func?.(args)
四、为变量赋默认值
以前,如果想为一个变量赋默认值,通常的做法是使用逻辑或操作符(||
)
let count = 0; let text = ""; let qty = count || 42; let message = text || "hi!"; console.log(qty); // 42,而不是 0 console.log(message); // "hi!",而不是 ""
空值合并操作符可以避免这种陷阱,其只在第一个操作数为null
或 undefined
时(而不是其它假值)返回第二个操作数:
let myText = ''; // An empty string (which is also a falsy value) let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello world let preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
转自:https://blog.csdn.net/czx3387170/article/details/121693204