我想用一个JavaScript数组列出一年中的几个月,但我仍然坚持如何使Jan月1而不是0月 [英] I want to list out the months of the year using a JavaScript array, but I am stuck on how to make Jan month 1 instead of month 0

查看:47
本文介绍了我想用一个JavaScript数组列出一年中的几个月,但我仍然坚持如何使Jan月1而不是0月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像问题所说的那样,我试图用月份名称的相应缩写来列出一年中的月份,但我仍然坚持如何使警报打印'月1是1月'而不是'月0是扬。这是我的代码中代码中的代码,结果是这个。如何从1月份的1月开始获得结果?谢谢

Like the question says, I am trying to list the months of the year with the corresponding abbreviation of the month name, but I am stuck on how to make the alert print 'Month 1 is Jan' instead of 'Month 0 is Jan'. This is my code within tags in my code, and the result is this. How can I get the result to begin from Month 1 for January? Thanks

        var months =["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
        var message = "";
        for (i in months) {
            message += 'Month ' + i + ' is ' + months[i] + '\n';
        }
        alert(message);


推荐答案

不要使用 for..in 循环迭代数组。它被设计为迭代对象键,并使 i 成为一个字符串(因此为什么 i + 1 不是工作)。

Don't use a for..in loop to iterate an array. It's designed to iterate over object keys, and will make i be a string (hence why i + 1 isn't working).

使用普通的代表循环:

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var message = "";
for (var i = 0; i < months.length; i++) {
  message += 'Month ' + (i + 1) + ' is ' + months[i] + '\n';
}
alert(message);

这篇关于我想用一个JavaScript数组列出一年中的几个月,但我仍然坚持如何使Jan月1而不是0月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆