理解对象字面量

4

在练习几个例子时,我遇到了以下的例子:

var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object[foo] = 'value';
alert(object[bar]);

两个对象foo和bar被创建,我不明白为什么alert(object[bar]);输出的是"value"。foo和bar之间有什么联系?

另外,稍微变化一下会得到"undefined"的输出,如下例所示。

var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object["foo"] = 'value';
alert(object[bar]);

默认情况下,[] 符号可以使用字符串 "right"。那么,["some_property"][some_property] 是相同的吗?


5
foobar之间的联系在于,它们在转换为字符串时(所有属性键都是字符串)产生相同的结果。 - Bergi
4
“*arent ["some_property"] and [some_property] the same?*” - 不是。 - Bergi
顺便提一下,如何将“Object”转换为原始类型由“valueOf”或“toString”方法规定(如果两者都定义了,则前者优先于后者)。 - user6445533
@LUH3417:并不总是,这取决于上下文。 - Felix Kling
@Felix 请给出一个这样的上下文。我渴望学习。 - user6445533
1
@LUH3417:''+foo 会先调用 foo.valueOf,但 String(foo) 会先调用 foo.toString - Felix Kling
2个回答

6
使用方括号表示法时,方括号中的任何内容都会转换为字符串。然后使用该字符串来查找具有相同名称的属性。
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};

object[foo] = 'value';
// foo is an object, so it's automatically turned into the string "[object Object]"
// so the above code is equivalent to `object["[object Object]"] = 'value';`

alert(object[bar]);
// bar is also an object, so is converted into the same string
// the above code is also equivalent to `alert(object["[object Object]"]);` which of course accesses that same value

var blah = "not blah";
object.blah = 1;
object["blah"] = 1;

object[blah];
// a variable is used.
// therefore the value of that variable is what the assessor is looking for, not the name of the variable.
// so the above code is equivalent to `object["not blah"];`.

0

一个对象的键只能是字符串*,因此当您使用不是字符串的值访问对象的属性时,它会被转换为字符串。

在ECMAScript 6中,您可以使用Map,它类似于对象,但您可以使用任何值作为键。例如:

const foo = {unique_prop: 1}
const bar = {unique_prop: 2}
const map = new Map()
map.set(foo, 'value')
console.log(map.get(bar)) // undefined

* 在ECMAScript 6中,您也可以使用符号,但这与本文无关。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接