在练习几个例子时,我遇到了以下例子:
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]
吗?
答案 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)