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
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. Commented Sep 15, 2020 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. Commented Sep 15, 2020 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). Commented Sep 15, 2020 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.) Commented Sep 15, 2020 at 22:47
  • thanks for the anwsers! it definetly got mee more aware of the course im following. thnaks again! Commented Sep 15, 2020 at 23:42

1 Answer 1

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>") 
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.