当要测试的变量为 null 时,JavaScript returns 中的可选链接未定义而不是 null

Optional Chaining in JavaScript returns undefined instead of null when the variable to be tested is null

所以,我正在阅读 JavaScript 中的可选链接,一个问题突然出现在我的脑海中。

考虑以下代码:

let person = null
let street = person?.street // returns undefined

我的问题是,如果变量 person 开头是 null,那么为什么执行可选链接结果会将变量设置为 undefined 而不是 null?

如果这个人是undefined,那么我想,对我来说,设置为undefined是合理的,因为变量当然是undefined,如下所示:

let person
let street = person?.street // returns undefined 

PS: 对不起,如果这是一个愚蠢的问题,如果有人同意我会删除它。 :)

PPS:如果重复此问题,请删除 link,我会试一试。非常感谢。

请阅读有关 optional chaining 的手册。

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

结果是 undefined 而不是 null 的原因是可选链 (?.)。


如果可选链接不可用,您的代码将导致错误,提示 null 没有属性。

const person = null;
person.street // ERROR!

但是,由于您有可选的链接,它只会导致 undefined

const person = null;
person?.street // undefined

这就是可选链接导致 undefined 的原因(如果值为 nullundefined);以避免抛出错误!

希望这能回答您的问题!

可选链不会计算为访问 属性 的空值,而是计算为 undefined - 就像当 属性 时得到 undefined对象中不存在。

从概念上讲,认为 person?.street 不是

person && person.street

而是

(person ?? {}).street

虽然准确(尤其是当进一步链接时,因为它 short-circuit 而不是评估链的其余部分)它确实是

person != null ? person.street : undefined

另见 FAQ on the optional chaining proposal:

Why does (null)?.b evaluate to undefined rather than null?

Neither a.b nor a?.b is intended to preserve arbitrary information on the base object a, but only to give information about the property "b" of that object. If a property "b" is absent from a, this is reflected by a.b === undefined and a?.b === undefined.

In particular, the value null is considered to have no properties; therefore, (null)?.b is undefined.