Using an object as a property key in JavaScript

What happens in this code?

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

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

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

In particular, why using search bin creturns the value that was stored in the property a?

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

I tested this in Chrome / Node and in Firefox.

+5
source share
2 answers

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

Javascript objects only allow string keys, so your object will first be forcibly bound to the string.

In particular, why using the search b in c returns the value that was stored in the property?

A string representation {a: 1}and {b: 2}equal "[object Object]", so the property is overwritten.

: ( , ), JSON:

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

, , . , , .

+10

, object.toString(), [Object Object],

, , "[Object Object]" "[Object Object]".

+2

All Articles