在JavaScript中使用对象作为属性键 [英] Using an object as a property key in JavaScript

查看:468
本文介绍了在JavaScript中使用对象作为属性键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码中发生了什么?

var a = {a:1};
var b = {b:2};
var c = {};

c[a] = 1;
c[b] === 1 // true!

c[b] = 2;
c[a] === 2 // true!

具体来说,为什么使用查找 b c 中返回存储在 a 属性中的值?

Specifically, why does using looking up b in c return the value that was stored in a property of a?

在JavaScript中使用对象作为属性的键是什么意思?

What does it mean to use an object as a key to a property in JavaScript?

我在Chrome / Node和Firefox中测试了这个。

I've tested this in Chrome/Node and in Firefox.

推荐答案


在JavaScript中使用对象作为属性的关键是什么意思?

What does it mean to use an object as a key to a property in JavaScript?

Javascript对象只允许使用字符串键,因此您的对象将首先被强制转换为字符串。

Javascript objects only allow string keys, so your object will first be coerced to a string.


具体来说,为什么在c中使用查找b会返回存储在属性中的值?

Specifically, why does using looking up b in c return the value that was stored in a property of a?

{a:1} {b:2} 的字符串表示形式 both [object Object],因此,该属性被覆盖。

The string representation of {a: 1} and {b: 2} are both "[object Object]", thus, the property is overwritten.

编辑: 如果你就是我需要使用对象作为键(我希望另一种解决方案,如果可能的话),你可以使用对象的JSON表示:

If you really need to use objects as keys (I would prefer another solution, if possible), you could use the object's JSON representation:

c[JSON.stringify(a)] = 1
c[JSON.stringify(b)] = 2

但是,再次尝试考虑不同的方法。也许对象具有除对象本身之外的唯一标识符。

But, again, try to think of a different approach. Perhaps the objects have unique identifiers other than the object itself.

这篇关于在JavaScript中使用对象作为属性键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆