[英]Understanding Javascript Object Code Snippet
我在Mozilla开发人员网络(MDN)上遇到了此代码段 ,并竭尽全力试图弄清楚为什么结果确实是“有价值的”
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; object[foo] = 'value'; console.log(object[bar]);
如果有人能开导我,我将不胜感激!
object[foo] = 'value';
您只能使用字符串作为标识符,因此,当上述运行时,JavaScript在内部调用ToString
方法,该方法表示"[object Object]"
。 这就是对象的表示方式。
现在,当您执行object[bar]
, bar.toString()
也是"[object Object]"
,并且由于'value'
以"[object Object]"
作为键存储,因此将返回它。
如果您在控制台中有个快速浏览,您会看到这是因为foo
被强制转换为string
(因为Javascript中的所有键都是字符串**),默认为[object object]
。 字符串[object object]
对于每个对象都是相同的,因此foo
似乎是bar
,但实际上不是。 查看以下输出:
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {}; object[foo] = 'value'; var output = document.getElementById('p') for(thing in object){ output.textContent += thing + " = " + object[thing]; }
<p id='p'></p>
**我认为ES6有一种使用{[func]: value}
语法设置计算键的方法,但是我还没有对此进行深入研究,所以请为我可能的不正确之处辩解。
您可以通过3个小型实验来了解发生了什么:
在您创建的每个对象上调用toString()的结果是什么?
foo.toString()
, bar.toString()
和object.toString()
将输出:
[object Object]
object[{}]
的结果是什么?
它也是"value"
,因为运行时用于存储值的键实际上是[object Object]
让我们更改toString的行为,看看会发生什么。
Object.prototype.toString = function(){ return this.unique_prop; }; // Re run the code object[foo] = "value"; console.log(object[bar]); // Returns undefined // Value was stored under the key "1" console.log(object[1]); // Returns "value"
因为此对象中的键是foo和bar对象的字符串表示形式,例如Object {[object Object]: "value"}
。
如上所述,使用对象设置对象属性结果可将键字符串化
> console.log(foo.toString())
[Log] [object Object]
所以object [foo]等效于
object["[object Object]"] = 'value';
但是,如果您实际上希望它们与众不同,则可以执行以下操作:
> console.log(JSON.stringify(foo))
[Log] {"unique_prop":1}
> object[JSON.stringify(foo)] = 'donkey'
> console.log(object)
[Log] {[object Object]: "value", {"unique_prop":1}: "donkey"}
> console.log(object[JSON.stringify(bar)])
[Log] undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.