简体   繁体   中英

how javascript add property to an object?

I was reading javascript questions where i found this piece of code

var a={},
    b={key:'b'},
    c={key:'c'};

a[b] = 123;
a[c] = 456;

console.log(a[b]);      // o/p - 456

can anybody make me understand this code why and how it is printing 456 ?

And I think we can use dot ie ab = 123 and string a['b'] = 123 approach to add property to an object.

Both b and c resolve to the same string ( [object Object] ). Hence you are overwriting the same key.

And I think we can use dot ie ab = 123 and string a['b'] = 123 approach to add property to an object.

Yes you can, but a['b'] is very different from a[b] . The first one resolves to a key with a string value just as it shows ( 'b' ), where as the other one will depend on the stringified value of the variable b (in this case is [object Object] ).

For really using the content of the object, you may use the stringified version.

 var a = {}, b = { key: 'b' }, c = { key: 'c' }; a[JSON.stringify(b)] = 123; a[JSON.stringify(c)] = 456; console.log(a[JSON.stringify(b)]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM