Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why a[c] override a[b]? [duplicate]

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
like image 861
user2734550 Avatar asked Mar 26 '15 18:03

user2734550


1 Answers

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
like image 133
Oriol Avatar answered Oct 07 '22 16:10

Oriol