0

i'm new to JavaScript. Im trying to make a loop that prints every month and also numbers them, but i end up getting a concatenation of the numbers. here's my code

var months = ['january', 'february', 'march','april',
                    'may', 'june', 'july', 'august',
                    'september', 'october', 'november, 'december'];
        for(i in months){
            document.write((i+1)+'.- '+months[i]);
            document.write('<br >')
        }

and my output is like this:

01.- janury
11.- february
21.- march
.... etc
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
Santiago A
  • 7
  • 1
  • 5
  • 3
    Don’t use `for in` to iterate over arrays – it’s for iterating over properties of objects. `for (var i = 0; i < months.length; i++)` to match the existing code, but really, you need to find a more up-to-date resource for learning JavaScript. Anything that teaches `document.write` is probably outdated. – Ry- Sep 15 '20 at 22:47
  • 1
    The index of a for-in loop is always a string, and when you add a string to a number it concatenates them. – John Montgomery Sep 15 '20 at 22:47
  • 1
    `for(i in obj)` iterates keys, and they are Strings. When used on Arrays, they are still Strings. That's why they "concatenate"... + the order is not guaranteed. Try (+i+1). – iAmOren Sep 15 '20 at 22:47
  • (The accepted answer on the linked duplicate offers several options, but only #3 is correct. *Don’t* continue using a `for in` loop with a cast to number.) – Ry- Sep 15 '20 at 22:47
  • thanks for the anwsers! it definetly got mee more aware of the course im following. thnaks again! – Santiago A Sep 15 '20 at 23:42

1 Answers1

0

This code will give you the desired result, changing it to a standard for loop:

var months = ['january', 'february', 'march','april', 'may', 'june', 'july', 'august' 'september', 'october', 'november', 'december'];

for (i=0; i < months.length; i++) {
    document.write(i+1 + ".- " + months[i] + "<br>") 
};
PsiKai
  • 1,803
  • 1
  • 5
  • 19