-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);
RobG
  • 142,382
  • 31
  • 172
  • 209
theJcode24
  • 33
  • 8

1 Answers1

2

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).

Use a normal for loop:

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);
4castle
  • 32,613
  • 11
  • 69
  • 106
  • Wow thanks so much for the answer! I tried changing to a while or do while loop, but I didn't think about the regular for loop. – theJcode24 Jun 16 '16 at 19:47
  • Btw you can convert a string easily to a number with the unary plus `+i`, but there are still [several reasons](http://stackoverflow.com/a/3010848/5743988) not to use `for..in` with arrays. – 4castle Jun 16 '16 at 20:05
  • Sorry what is a unary plus `+i`? – theJcode24 Jun 17 '16 at 07:07
  • Read [this](http://stackoverflow.com/a/5450116/5743988). When you put a plus `+` next to a variable, it converts the variable to a number type. So `+i` would convert `i` to a number. When you were using the `for..in` loop, one option would have been to do `(+i + 1)` – 4castle Jun 17 '16 at 12:19