如何有效填充具有许多静态键/值对的Javascript对象文字? [英] How to fill a Javascript object literal with many static key/value pairs efficiently?
问题描述
创建Javascript对象的典型方法如下:
The typical way of creating a Javascript object 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屋!