Javascript - 将数字转换为月份名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49915384/
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-10-29 08:50:02  来源:igfitidea点击:

Javascript - convert number to month name

javascriptloopsforeachnumbers

提问by peaceduck

I have a very simple problem but for some reason I can't find the answer for it.

我有一个非常简单的问题,但由于某种原因我找不到答案。

label.forEach(function(value){
    months.push(value['month']);
    revenue.push(value['revenue']);
});

The labelis an array of numbers and revenue, in my case this is

label是一组数字和收入,在我的情况下是

[
{month: 9, revenue: 400}, 
{month: 11, revenue: 500},
{month: 12, revenue: 600}
]

This is a forEach loop in javascript, it pushes revenue and a month number into two seperate arrays, the problem is that the month is a number (e.g. 12) but I want the .push() to push a month name instead (December), I can't seem to find anything so I was hoping anyone here could help me out.

这是 javascript 中的 forEach 循环,它将收入和月份数字推送到两个单独的数组中,问题是月份是一个数字(例如 12),但我希望 .push() 改为推送月份名称(12 月) ,我似乎找不到任何东西,所以我希望这里的任何人都可以帮助我。

回答by O?uzhan

var months = [ "January", "February", "March", "April", "May", "June", 
           "July", "August", "September", "October", "November", "December" ];

var selectedMonthName = months[value['month']];

look at the links

看看链接

stack 1

堆栈 1

回答by Dineth Cooray

This can be easily done using moment.js.

这可以使用 moment.js 轻松完成。

var months = [];
months.push(moment().month(0).format("MMMM"));
console.log(months);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

回答by Mamun

You can try the following:

您可以尝试以下操作:

var label = [{month: 9, revenue: 400}, 
            {month: 11, revenue: 500},
            {month: 12, revenue: 600}]

var months = [];
var revenue = [];
var m = [ "January", "February", "March", "April", "May", "June", 
           "July", "August", "September", "October", "November", "December" ];

label.forEach(function(value){
    var monthName = m[value.month - 1];
    months.push(monthName);
    revenue.push(value.revenue);
});

console.log('Months Array: ', months);
console.log('Revenue Array:', revenue);

回答by Arslan Nawaz

    <script src="https://momentjs.com/downloads/moment.min.js"></script>

    var monthNumber='03';
    var month = [ "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December" ];
    var monthIndex = moment().month(monthNumber[1]-1).format("M");
    var selectedMonthName = month[monthIndex-1];
    alert(selectedMonthName);