3

Initializing a map having string keys can be performed as following in Javascript:

var xxx = {
    "aaa" : ["a1","a2","a3"],
    "bbb" : ["b1","b2","b3"],
    "ccc" : ["c1","c2","c3"],
    ...
};

I need to initialize some map with integer keys, something like:

var xxx = {
    0 : ["a1","a2","a3"],
    1 : ["b1","b2","b3"],
    2 : ["c1","c2","c3"],
    ...
};

Of course, I could proceed with an array like this:

xxx[0]=["a1","a2","a3"];
xxx[1]=["b1","b2","b3"];
xxx[2]=["c1","c2","c3"];
...

but the issue is that it makes the initialization code long. I need to squeeze all the bytes I can from it, because I need to push this object on the user side and any saved byte counts.

The xxx object needs to be initialized with n arrays, and each entry has a unique associated id between 0 and n-1. So, there is a one to one mapping between the id I can use and the arrays, and these ids are consecutive from 0 to n-1, which makes me think I could use an array instead of a Javascript 'map'.

I have noticed that one can push objects into an array. May be I could use something like this:

var xxx = [];
xxx.push(["a1","a2","a3"],["b1","b2","b3"],["c1","c2","c3"],...);

Is this a proper to achieve my objective or is there something smarter in Javascript? Thanks.

P.S.: Later, xxx will be referenced with something like xxx[2], xxx[10], etc...

4

1 回答 1

3

不过,这让我觉得比使用字符串或整数键更干净,除非您需要在 上添加其他属性xxx

var xxx = [
    ["a1","a2","a3"],
    ["b1","b2","b3"],
    ["c1","c2","c3"]
    //...
];

只需制作xxx一个包含数组的数组。例如,您可以通过xxx[1][2](因为xxx[1] == ["b1", "b2", "b3"].)获得“b3”

于 2013-07-30T11:14:32.543 回答