views:

70

answers:

3

How can i make it nicer?

var month = new Array();

month['01']='Jan';
month['02']='Feb';
month['03']='Mar';

etc. Itd be nice to do it like:

var months = new Array(['01','Jan'],['02','Feb'],['03','Mar']);

For example. anyway like that to simplify it?

+4  A: 

this should do it ..

var months = {'01':'Jan', '02':'Feb'};
alert( months['01'] );
Gaby
damn it, duh, JSON... Thanks!
Oscar Godson
Oh, and ill update you as the right answer after I wait the 10 mins it says I have to wait...
Oscar Godson
@oscar, no problem, i am patient :p
Gaby
+1  A: 

Don't use an Array unless you're using real numeric indexes. Try this:

var month = {
    '01': 'Jan',
    '02': 'Feb',
    // ...
    '12': 'Dec'
};

Personally, though, I would wrap this kind of logic in a function:

var monthNames = ['Jan', 'Feb', /* ... */ 'Dec'];
function getMonthName(n) {
    return monthNames(n - 1);
}

alert(getMonthName(1)); // 'Jan'

That way, you never have to think about the underlying data structure, or worry about changing it later.

harto
+3  A: 

why not:

var month = [
  'Jan', 
  'Feb', 
  // ...
  'Dec'];

To get the month name from the number you'd do something like:

var monthNum = 2; // February
var monthShortName = month[monthNum-1];
no
Imagine that, using numerical indices on an array object. Whatever next!?
Andy E
Object indexes Andy, comon. `var one = {'1': 'one'}; var month = {}; month[one] = "Jan";`
Anurag
Hahah Anurag I think I'm going to be sick
no
@Andy E - dude what happened to your head?!
Matt Ball
@bears: horrific bear accident. If only I'd seen your screen name beforehand. Fortunately my head was intact - my body was just holding me back anyway ;-)
Andy E