use*_*764 4 javascript javascript-objects ecmascript-6
在练习几个例子时,我遇到了以下例子:
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object[foo] = 'value';
alert(object[bar]);
Run Code Online (Sandbox Code Playgroud)
其中创建了两个对象foo和bar.我没有得到多么警觉(对象[bar]); 是"价值".什么是foo和bar之间的链接.
此外,稍微变化会使输出为"未定义",如下例所示.
var foo = {unique_prop: 1};
var bar = {unique_prop: 2};
var object = {};
object["foo"] = 'value';
alert(object[bar]);
Run Code Online (Sandbox Code Playgroud)
默认情况下,[]表示法可以使用正确,不正确["some_property"]和[some_property]相同的字符串?
使用方括号表示法时,方括号内的任何内容都将转换为字符串.然后该字符串用于查找称为相同内容的属性.
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"];`.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |