我很想知道在 javascript 中通过未定义键或空键访问对象时正确的行为是什么。
我检查了它在 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'}
然后,似乎 undefined
和 null
被强制转换为字符串 'undefined'
和 'null'
.但是,如果我阅读 ecmascript specs我看到使用了 RequireObjectCoercible
。读书RequireObjectCoercible specs ,我看到当它作为参数传递 undefined 或 null 时,它会抛出 TypeError 异常。
因此我不明白为什么我在检查时会重现另一个行为。
编辑:
感谢 Andreas 和 Bergi
我理解这种行为是因为:
12.3.2.1 Runtime Semantics: Evaluation
[...]
- Let propertyKey be ToPropertyKey(propertyNameValue).
7.1.14 ToPropertyKey ( argument )
[...]
- Return ToString(key).
7.1.12 ToString ( argument )
The abstract operation ToString converts argument to a value of type String according to Table 12:
[...]
Undefined | Return "undefined".
Null | Return "null".
对吧?
最佳答案
RequireObjectCoercible
是在构造属性引用之前在基值上调用的,而不是在属性上调用的。 obj
可强制转换为对象 :-) 当您执行 undefined.x
或 null[y]
之类的操作时,它确实会抛出。
关于javascript - ecmascript 5 或 6 中未定义键和空键的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370284/