理解对象文字

时间:2016-09-01 10:00:37

标签: javascript ecmascript-6 javascript-objects

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

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

创建了两个对象foo和bar。我没有得到多么警觉(对象[bar]);是"价值"。 什么是foo和bar之间的链接。

此外,稍微变化会使输出为" undefined"如下例所示。

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

默认情况下,[]表示法可以使用正确的字符串,不是["some_property"][some_property]吗?

2 个答案:

答案 0 :(得分: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"];`.

答案 1 :(得分: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中,您也可以使用symbols,但这里不相关。