I don't understand why the output is 456. I think the b in a[b] is a property of a object, and c is another property of a. They are not related to the var b and c at all. But why a.c override a.b?
var a={},
b={key:'b'},
c={key:'c'};
a[b]=123;
a[c]=456;
console.log(a[b] === 456); //true
That's because property names are strings, but your b
and c
are objects. Therefore, they are stringified:
b + ''; // "[object Object]"
c + ''; // "[object Object]"
b + '' === c + ''; // true
Since they become the same string, the initial value is overridden.
Instead, you may consider using ECMAScript 6 Maps, which allow you to use any value as keys:
var a = new Map(),
b = {key: 'b'},
c = {key: 'c'};
a.set(b, 123);
a.set(c, 456);
a.get(b); // 123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With