【发布时间】:2017-02-28 16:23:11
【问题描述】:
密切相关的问题:
- associative array versus object in javascript
- Why does JavaScript not throw an exception for this code sample?
- javascript array associative AND indexed?
我有以下代码示例:
var someVariable = {abc: "def", ghi: "jkl"}
someVariable["SomeProperty"] = "dfsdfadsd"
alert(someVariable["SomeProperty"])
var someOtherVariable = { abcd: "defsd", ghij: "dfsdfdss" }
someOtherVariable.SomeOtherProperty = "adfsdfsd"
alert(someOtherVariable.SomeOtherProperty);
alert(someOtherVariable["SomeOtherProperty"])
他们都做着他们看起来的样子——他们把一个属性附加到他们各自的对象上。 alert 在每种情况下都显示预期的字符串。我从相关问题的理解是两者之间没有功能差异。
我在 W3Schools 的JavaScript arrays tutorial 中也遇到了如下语句:
许多编程语言都支持带有命名索引的数组。
具有命名索引的数组称为关联数组(或哈希)。
JavaScript 确实不支持具有命名索引的数组。
在 JavaScript 中,数组总是使用编号索引。
如果是这样,为什么这里完全允许数组语法? (同样,我对相关问题的理解是,关联数组和 JavaScript 对象之间的实际区别至少有点模糊,这就是 JavaScript “在后台”实现对象属性的方式。
据我所知(如果我错了,请纠正我,因为 JavaScript 不是我的主要语言),不可能做你期望能够用数组做的其他事情(例如迭代带有for 循环),那么为什么还要同时使用两种语法呢?在 C# 中,您可以执行以下操作:
// A C# dictionary is basically an associative array
Dictionary<string, int> dict = new Dictionary<string, int>();
// Fill dictionary ...
foreach (string key in dict.Keys) {
int value = dict[key];
// Do something with the value
}
但我不知道用 JavaScript 属性做类似事情的方法。在 C# 中这种语法显然是必要的(键绝对是dict 的 not 属性),但是为什么 JavaScript 有这个(假设它们完全等价)?我是否遗漏了什么,或者这实际上是完全多余的?
【问题讨论】:
-
这是括号符号
-
@baao 谢谢,这可能是更准确的描述方式
标签: javascript arrays object