ecmascript 5或6中未定义键和null键的行为

Behaviour of undefined and null keys in ecmascript 5 or 6

本文关键字:null 未定义 ecmascript      更新时间:2023-09-26

我很想知道当javascript中的未定义或null键访问对象时,正确的行为是什么。

我检查了它在Chrome 46、Firefox 42和节点0.12.0中的行为,结果是一样的:

var obj = {};
obj[undefined] = 'foo';
obj[undefined]; // 'foo'
obj['undefined']; // 'foo'
obj; // {undefined: 'foo'}

或:

var obj = {};
obj[null] = 'foo';
obj[null]; // 'foo'
obj['null']; // 'foo'
obj; // {null: 'foo'}

然后,似乎undefinednull被强制为字符串'undefined''null'。但是,如果我阅读ecmascript规范,就会发现使用了RequireObjectCoercible。阅读RequireObjectCoercible规范时,我发现当它作为参数传递未定义或null时,会引发TypeError异常。

因此,我不明白为什么我在检查时会重现另一种行为


编辑:

感谢Andreas和Bergi

我理解这种行为是因为:

12.3.2.1运行时语义:评估

[…]

  1. 让propertyKey为ToPropertyKey(propertyNameValue)

7.1.14 ToPropertyKey(参数)

[…]

  1. 返回ToString(键)

7.1.12 ToString(参数)

抽象操作ToString根据表12:将参数转换为String类型的值

[…]

未定义|返回"未定义";。

Null |返回"空";。

对吧?

RequireObjectCoercible是在构造属性引用之前对基值调用的,而不是对属性调用的。obj对一个对象是可强制的:-)当你做undefined.xnull[y]之类的事情时,它确实会抛出。