JavaScript 对象属性查找 - 语法重要吗?
这是一个关于 JavaScript (ECMAScript) 语言的基本问题,所以如果它是重复的,我提前道歉(一点搜索没有揭示我的确切问题)。
在 ECMAScript 中,我们可以使用两种基本语法形式来获取/设置对象的属性,并且它们似乎具有完全相同的效果。由于我不太了解,我将它们称为“属性”和“关联数组”符号:
var o = {};
// Property notation.
o.foo = 'Foo'; // (set)
o.foo; // => "Foo" (get)
// Associative array notation.
o['bar'] = 'Bar'; // (set)
o['bar']; // => "Bar" (get)
// They seem to be interchangeable.
o['foo']; // => "Foo"
o.bar; // => "Bar"
这两种符号之间有什么真正的区别吗?显然,关联数组表示法允许我们查找对象上动态生成的键(并强制将其参数强制转换为字符串),而属性表示法使用文字,但这是唯一的区别吗?
This is a basic question about the JavaScript (ECMAScript) language so I apologize in advance if it's a duplicate (a little searching didn't reveal my exact question).
In ECMAScript we can use two basic syntactic forms to get/set properties on an object and they seem to have the exact same effect. Since I don't know better, I'll call them "property" and "associative array" notations:
var o = {};
// Property notation.
o.foo = 'Foo'; // (set)
o.foo; // => "Foo" (get)
// Associative array notation.
o['bar'] = 'Bar'; // (set)
o['bar']; // => "Bar" (get)
// They seem to be interchangeable.
o['foo']; // => "Foo"
o.bar; // => "Bar"
Are there any real differences between these two notations? Obviously, the associative array notation allows us to lookup dynamically generated keys on the object (and forcibly casts its argument to a string) whereas the property notation uses a literal but is that the only difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的;它们是相同的。
You are correct; they are identical.