user2734550 user2734550 - 1 year ago 83
Javascript Question

Why a[c] override a[b]?

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={},


console.log(a[b] === 456); //true

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download