可选链操作符( ?.
)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?.
操作符的功能类似于 .
链式操作符,不同之处在于,在引用为空(nullish ) (null
或者 undefined
) 的情况下不会引起错误,该表达式短路返回值是 undefined
。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined
。
举个简单例子:let nestedProp = obj.first && obj.first.second;
为了避免报错,在访问obj.first.second
之前,要保证 obj.first
的值既不是 null
,也不是 undefined
。如果只是直接访问 obj.first.second
,而不对 obj.first
进行校验,则有可能抛出错误。
有了可选链操作符(?.
),在访问 obj.first.second
之前,不再需要明确地校验 obj.first
的状态,再并用短路计算获取最终结果:let nestedProp = obj.first?.second;
通过使用 ?.
操作符取代 .
操作符,JavaScript 会在尝试访问 obj.first.second
之前,先隐式地检查并确定 obj.first
既不是 null
也不是 undefined
。如果obj.first
是 null
或者 undefined
,表达式将会短路计算直接返回 undefined
。
这等价于以下表达式,但实际上没有创建临时变量:
let temp = obj.first; let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
注意:可选链不能用于赋值
let object = {};
object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment;
短路计算
当在表达式中使用可选链时,如果左操作数是 null
或 undefined
,表达式将不会被计算,例如:
let potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; console.log(x); // x 将不会被递增,依旧输出 0