如何有效地填充许多静态键/值对的Javascript地图? [英] How to fill a Javascript map with many static key/value pairs efficiently?
问题描述
创建Javascript地图的典型方式如下:
The typical way of creating a Javascript map is the following:
var map = new Object();
map[myKey1] = myObj1;
map[myKey2] = myObj2;
我需要创建一个这样的地图,其中键和值都是字符串。我有一个很大但静态的对,可以添加到地图中。
I need to create such a map where both keys and values are Strings. I have a large but static set of pairs to add to the map.
有没有办法在Javascript中执行这样的操作:
Is there any way to perform something like this in Javascript:
var map = { { "aaa", "rrr" }, { "bbb", "ppp" } ... };
或者我必须为每个条目执行这样的操作:
or do I have to perform something like this for each entry:
map["aaa"]="rrr";
map["bbb"]="ppp";
...
基本上,剩下的Javascript代码将循环遍历该地图,并根据到运行时已知的标准。如果这个循环工作有更好的数据结构,我也很感兴趣。我的目标是最小化代码。
Basically, remaining Javascript code will loop over this map and extract values according to criterias known 'at runtime'. If there is a better data structure for this looping job, I am interested too. My objective is to minimize code.
推荐答案
JavaScript的对象文字语法,通常用于实例化对象(严重地,没有人使用 new Object
或 new Array
)如下:
JavaScript's object literal syntax, which is typically used to instantiate objects (seriously, no one uses new Object
or new Array
), is as follows:
var obj = {
'key': 'value',
'another key': 'another value',
anUnquotedKey: 'more value!'
};
对于数组,它是:
var arr = [
'value',
'another value',
'even more values'
];
如果您需要对象内的对象,那也很好:
If you need objects within objects, that's fine too:
var obj = {
'subObject': {
'key': 'value'
},
'another object': {
'some key': 'some value',
'another key': 'another value',
'an array': [ 'this', 'is', 'ok', 'as', 'well' ]
}
}
能够实例化静态数据的方便方法是导致 JSON数据格式。
This convenient method of being able to instantiate static data is what led to the JSON data format.
JSON有点更挑剔,键必须用双引号括起来,以及字符串值:
JSON is a little more picky, keys must be enclosed in double-quotes, as well as string values:
{"foo":"bar", "keyWithIntegerValue":123}
这篇关于如何有效地填充许多静态键/值对的Javascript地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!