简体   繁体   English

JavaScript中的对象属性值

[英]Object Property Value in javascript

How property value being assigned in below code: 在下面的代码中如何分配属性值:

var foo = {};
var bar = {};
var obj = {};

obj[foo] = "Nishan";
obj[bar] = "Manis";


console.log(obj[foo]);

Why it giving output "Manis" 为什么给出输出“ Manis”

var foo = {};
var bar = {};
var obj = {};

obj.foo = "Nishan";
obj.bar = "Manis";

console.log(obj.foo);

Output: "Nishan"

What is difference between declare property of object by using "." 使用“。”声明对象的属性之间有什么区别? and "[]" Ex: obj.far = "Nish" and obj[far] = "Nish" 和“ []”,例如:obj.far =“ Nish”和obj [far] =“ Nish”

var foo = {};
var bar = {};
var obj = {};

obj.foo = "Nishan";
obj.bar = "Manis";

console.log(obj[foo]);

Giving undefined 给未定义

An object is valid as a key only because it's converted to a string, and the string representation of an object is [object Object] , so what you're doing is equal to 仅因为将对象转换为字符串,并且对象的字符串表示形式为[object Object] ,否则该对象才可用作键,因此您所做的等于

var obj = {};

obj[`[object Object]`] = "Nishan";
obj[`[object Object]`] = "Manis";

console.log( obj[`[object Object]`] ); // returns Manis

So basically you're overwriting the key / value pair as the string representation of foo and bar is the same thing, they are both converted to [object Object] 所以基本上您要覆盖键/值对,因为foobar的字符串表示是同一回事,它们都转换为[object Object]

EDIT : 编辑:

In the second and third example you do something like 在第二个和第三个示例中,您执行类似

var foo = {};

obj.foo = "something";

but when you're using dot notation you can declare any property you want, and the property foo on the object has nothing to do with the variable foo declared above, they are not even remotely related, you might as well do 但是,当您使用点表示法时,可以声明所需的任何属性,而对象上的属性foo与上面声明的变量foo无关,它们甚至没有远程关联,您也可以这样做

var foo = {};

obj.didgeridoo = "something";

the relevance is the same, nothing. 相关性是相同的,什么都没有。

When you access a property using square bracket notation, you have to pass a string in. 使用方括号符号访问属性时,必须传入一个字符串。

foo and bar are both objects. foobar都是对象。

When you convert an object to a string, by default, you get a result like "[Object object]" . 默认情况下,将对象转换为字符串时,将得到类似于"[Object object]"

foo.toString() === bar.toString() so obj[foo] === obj[bar] . foo.toString() === bar.toString()所以obj[foo] === obj[bar]

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

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