开发者

Month Array in JavaScript Not Pretty

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?


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!


this should do it ..

var months = {'01':'Jan', '02':'Feb'};
alert( months['01'] );


Short Dynamic Solution:

Here's a dynamic solution that does not require hard-coding an array of months:

const month = f=>Array.from(Array(12),(e,i)=>new Date(25e8*++i).toLocaleString('en-US',{month:f}));

Test Cases:

// Using Number Index:

month`long`[0];    // January
month`long`[1];    // February
month`long`[2];    // March

month`short`[0];   // Jan
month`short`[1];   // Feb
month`short`[2];   // Mar

month`narrow`[0];  // J
month`narrow`[1];  // F
month`narrow`[2];  // M

month`numeric`[0]; // 1
month`numeric`[1]; // 2
month`numeric`[2]; // 3

month`2-digit`[0]; // 01
month`2-digit`[1]; // 02
month`2-digit`[2]; // 03

// Using String Index:

let index_string = '01';

month`long`[index_string-1];    // January
month`short`[index_string-1];   // Jan
month`narrow`[index_string-1];  // J
month`numeric`[index_string-1]; // 1
month`2-digit`[index_string-1]; // 01


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];


Here is very simple approach to get month name :

<script>
function getMonth(month){
    month = month-1;
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    if(months[month] != null){
        return months[month];
    }else{
        throw "Invalid Month No";
    }
}

try{
    monthName = getMonth(8);
    alert("Month Is : " + monthName);
}catch(e){
    console.log(e);
}
</script> 


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.


You can use nice library https://github.com/pret-a-porter/month-list

  • getMonthList('en', 'short') for short names ["Jan", "Feb", ...]
  • getMonthList('en', '2-digit') for numeric strings ["01", "02", ...]


Months in javascript for faster access O(1)

const months = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct",

"11": "Nov",

"12": "Dec", };


import java.util.*;

public class NumOfMonth
{
  public static void main(String args[]) {

    Scanner in = new Scanner (System.in);

    String months[] = {"","Jan", "Feb", "March", "april" , "june", "july", "august", "sept", "oct", "nov","Dec`1"};
    int m = 0;
    System.out.format("enter the number of month:");
    m = in.nextInt();
    System.out.println(months[m]);
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜