如何缩短将数字转换为月份名称的开关大小写块?

有没有一种方法可以在较少的行上编写此代码,但仍然易于阅读?

var month = '';

switch(mm) {
    case '1':
        month = 'January';
        break;
    case '2':
        month = 'February';
        break;
    case '3':
        month = 'March';
        break;
    case '4':
        month = 'April';
        break;
    case '5':
        month = 'May';
        break;
    case '6':
        month = 'June';
        break;
    case '7':
        month = 'July';
        break;
    case '8':
        month = 'August';
        break;
    case '9':
        month = 'September';
        break;
    case '10':
        month = 'October';
        break;
    case '11':
        month = 'November';
        break;
    case '12':
        month = 'December';
        break;
}

定义一个数组,然后通过索引获取。

var months = ['January', 'February', ...];

var month = months[mm - 1] || '';

那么不要使用数组:)

var objDate = new Date("10/11/2009"),
    locale = "en-us",
    month = objDate.toLocaleString(locale, { month: "long" });

console.log(month);

// or if you want the shorter date: (also possible to use "narrow" for "O"
console.log(objDate.toLocaleString(locale, { month: "short" }));

按照这个答案从David Storey的Date获取月份名称


尝试这个:

var months = {'1': 'January', '2': 'February'}; //etc
var month = months[mm];

请注意, mm可以是整数或字符串,它仍然可以工作。

如果您希望不存在的键导致空字符串'' (而不是undefined ),则添加以下行:

month = (month == undefined) ? '' : month;

的jsfiddle。

链接地址: http://www.djcxy.com/p/91757.html

上一篇: How to shorten switch case block converting a number to a month name?

下一篇: Sort JavaScript object by key