Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month Array in JavaScript Not Pretty

Tags:

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?

like image 446
Oscar Godson Avatar asked Jul 15 '10 23:07

Oscar Godson


People also ask

Can JavaScript arrays change size?

JavaScript allows you to change the value of the array length property. By changing the value of the length, you can remove elements from the array or make the array sparse.

Is JavaScript set faster than array?

Using Sets in ES6 to produce lists of unique objects is faster than using arrays, and less error prone than using objects.

What is the correct way to JavaScript array?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.


1 Answers

For a more natural approach, try this little snippet. It works with Date objects and just as a regular function:

'use strict';  (function(d){     var mL = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];     var mS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];      d.prototype.getLongMonth = d.getLongMonth = function getLongMonth (inMonth) {         return gM.call(this, inMonth, mL);     }      d.prototype.getShortMonth = d.getShortMonth = function getShortMonth (inMonth) {         return gM.call(this, inMonth, mS);     }      function gM(inMonth, arr){         var m;          if(this instanceof d){             m = this.getMonth();         }         else if(typeof inMonth !== 'undefined') {             m = parseInt(inMonth,10) - 1; // Subtract 1 to start January at zero         }          return arr[m];     } })(Date); 

You can directly copy and paste this, then use it like this:

var today = new Date(); console.log(today.getLongMonth()); console.log(Date.getLongMonth(9));          // September console.log(today.getShortMonth()); console.log(Date.getShortMonth('09'));      // Sept 

This technique will provide flexibility as to how you index and how you access it. When using the Date object it will work correctly, but if using it as a standalone function it considers the months in human readable format from 1-12.

Fiddle with it!

like image 104
Jim Buck Avatar answered Oct 01 '22 05:10

Jim Buck