我想用一个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);