在 JavaScript 关联数组中动态创建键
到目前为止我找到的所有文档都是更新已经创建的密钥:
arr['key'] = val;
我有一个像这样的字符串: " name = oscar "
我想最终得到这样的结果
{ name: 'whatever' }
: ,分割字符串并获取第一个元素,然后将其放入字典中。
代码
var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.
All the documentation I've found so far is to update keys that are already created:
arr['key'] = val;
I have a string like this: " name = oscar "
And I want to end up with something like this:
{ name: 'whatever' }
That is, split the string and get the first element, and then put that in a dictionary.
Code
var text = ' name = oscar '
var dict = new Array();
var keyValuePair = text.split(' = ');
dict[ keyValuePair[0] ] = 'whatever';
alert( dict ); // Prints nothing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
不知何故,所有示例虽然运行良好,但都过于复杂:
new Object()
。 它工作得很好,但是为什么要额外输入这些内容呢?这个问题被标记为“初学者”,所以让我们简单点。
在 JavaScript 中使用字典的超级简单方法或“为什么 JavaScript 没有特殊的字典对象?”:
现在让我们更改值:
删除值也很容易:
Somehow all examples, while work well, are overcomplicated:
new Array()
, which is an overkill (and an overhead) for a simple associative array (AKA dictionary).new Object()
. It works fine, but why all this extra typing?This question is tagged "beginner", so let's make it simple.
The über-simple way to use a dictionary in JavaScript or "Why doesn't JavaScript have a special dictionary object?":
Now let's change values:
Deleting values is easy too:
使用第一个例子。 如果该密钥不存在,则会添加该密钥。
会弹出一个包含“oscar”的消息框。
尝试:
Use the first example. If the key doesn't exist it will be added.
Will pop up a message box containing 'oscar'.
Try:
JavaScript 没有关联数组。 它有对象。
以下代码行都执行完全相同的操作 - 将对象上的“名称”字段设置为“orion”。
看起来您有一个关联数组,因为
Array
也是一个Object
- 但是您实际上根本没有将内容添加到数组中; 您正在对象上设置字段。现在已经清楚了,这是您的示例的可行解决方案:
JavaScript does not have associative arrays. It has objects.
The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.
It looks like you have an associative array because an
Array
is also anObject
- however you're not actually adding things into the array at all; you're setting fields on the object.Now that that is cleared up, here is a working solution to your example:
作为对 MK_Dev 的响应,我们可以迭代,但不能连续(为此,显然需要一个数组)。
快速 Google 搜索会显示JavaScript 中的哈希表。
用于循环哈希中的值的示例代码(来自上述链接):
In response to MK_Dev, one is able to iterate, but not consecutively (for that, obviously an array is needed).
A quick Google search brings up hash tables in JavaScript.
Example code for looping over values in a hash (from the aforementioned link):
原始代码(我添加了行号,以便可以参考它们):
几乎就在那里...
第 1 行:您应该对文本进行
trim
,使其成为name = oscar
.第 3 行:只要你的平等者周围总是就可以。
最好不要在第 1 行中
trim
。使用=
并修剪每个 keyValuePair在 3 之后和 4 之前添加一行:
第 4 行:现在变为:
第 5 行:更改为:
我试图说
dict[keyValuePair[0]]
不起作用。 您需要将一个字符串设置为keyValuePair[0]
并将其用作关联键。 这是我让自己工作的唯一方法。 设置完成后,您可以使用数字索引或键入引号来引用它。The original code (I added the line numbers so can refer to them):
Almost there...
line 1: you should do a
trim
on text so it isname = oscar
.line 3: okay as long as you always have spaces around your equal.
It might be better to not
trim
in line 1. Use=
and trim each keyValuePairadd a line after 3 and before 4:
line 4: Now becomes:
line 5: Change to:
I'm trying to say that the
dict[keyValuePair[0]]
does not work. You need to set a string tokeyValuePair[0]
and use that as the associative key. That is the only way I got mine to work. After you have set it up, you can either refer to it with numeric index or key in quotes.所有现代浏览器都支持 Map,是一个键/值数据结构。 使用 Map 比使用 Object 更好的原因有几个:
示例:
如果您希望垃圾收集未从其他对象引用的键,请考虑使用 WeakMap 而不是 Map。
All modern browsers support a Map, which is a key/value data structure. There are a couple of reasons that make using a Map better than Object:
Example:
If you want keys that are not referenced from other objects to be garbage collected, consider using a WeakMap instead of a Map.
我认为如果您像这样创建它会更好:
有关更多信息,请看一下:
JavaScript 数据结构 - 关联数组
I think it is better if you just created it like this:
For more info, take a look at this:
JavaScript Data Structures - Associative Array
这没问题,但它会迭代数组对象的每个属性。
如果您只想迭代 myArray.one、myArray.two... 属性,您可以这样尝试:
现在您可以通过 myArray["one"] 访问这两个属性,并且仅迭代这些属性。
This is ok, but it iterates through every property of the array object.
If you want to only iterate through the properties myArray.one, myArray.two... you try like this:
Now you can access both by myArray["one"] and iterate only through these properties.