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...

3
  • Why don't you use var xxx = {0 : ["a1","a2","a3"], ...}, i.e. your second example? Number literals are valid property names in object literals. See es5.github.io/#x11.1.5. Commented Jul 30, 2013 at 11:02
  • Well I thought one could not use integers as map keys. May be I am wrong... Commented Jul 30, 2013 at 11:04
  • 1
    Well, you can ;) Every property name is converted to a string anyway. I.e. {0: 'foo'} is the same as {"0": 'foo'}. And after all, arrays are just objects too. The elements of an array are nothing but properties with numeric names. But maybe using an array would make more sense anyway. Commented Jul 30, 2013 at 11:04

1 Answer 1

3

This strikes me as cleaner than using String or integer keys, though, unless you need to add additional properties on xxx:

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

Just make xxx into an array containing arrays. You can get at, say, "b3", via xxx[1][2] (because xxx[1] == ["b1", "b2", "b3"].)

Sign up to request clarification or add additional context in comments.

1 Comment

For the records, I have created a smalll jsfiddle to test the concept: jsfiddle.net/DVmHS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.