简体   繁体   English

javascript如何将属性添加到对象?

[英]how javascript add property to an object?

I was reading javascript questions where i found this piece of code 我正在阅读javascript问题,我找到了这段代码

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 ? 谁能让我理解这段代码为什么以及如何打印456

And I think we can use dot ie ab = 123 and string a['b'] = 123 approach to add property to an object. 而且我认为我们可以使用ab = 123字符串 a['b'] = 123方法来向对象添加属性。

Both b and c resolve to the same string ( [object Object] ). bc解析为相同的字符串( [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. 而且我认为我们可以使用点即ab = 123和字符串a ['b'] = 123方法来向对象添加属性。

Yes you can, but a['b'] is very different from a[b] . 是的,你可以,但是a['b']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] ). 第一个解析为具有字符串值的键,就像它显示( 'b' ),其中另一个将取决于变量b的字符串化值(在这种情况下是[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)]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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