JavaScript 中的月份数组不漂亮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3260939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:55:41  来源:igfitidea点击:

Month Array in JavaScript Not Pretty

javascriptarraysdateobject

提问by Oscar Godson

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?

例如。无论如何,要简化它吗?

回答by Jim Buck

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

为了更自然的方法,试试这个小片段。它适用于Date对象,就像普通函数一样:

'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 Dateobject it will work correctly, but if using it as a standalone function it considers the months in human readable format from 1-12.

这种技术将为您如何编制索引以及如何访问它提供灵活性。使用该Date对象时,它将正常工作,但如果将其用作独立函数,它会考虑 1-12 之间人类可读格式的月份。

Fiddle with it!

摆弄它!

回答by Gabriele Petrioli

this should do it ..

这应该这样做..

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

回答by Grant Miller

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

回答by Dagg Nabbit

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

回答by harto

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.

这样,您就不必考虑底层数据结构,也不必担心以后更改它。

回答by Sunny S.M

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> 

回答by jessa

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