8

I made an array with several strings as values so it becomes one really long line that takes a while to scroll through. To put it on multiple lines I searched and found that I can use a + sign to link the lines, but I'm having a problem. Here's a small example:

<script type="text/javascript">
var x;
var colorArr=["Red","Orange","Yellow",+
"Green","Blue","Purple"];
for(x=0;x<6;x++)
document.write(colorArr[x]+"<br/>");
</script>

This outputs:

Red
Orange
Yellow
NaN
Blue
Purple

Basically whichever element is the first on the line becomes undefined for some reason. How do I do this the correct way?

0

3 Answers 3

18

You don't need the +, just flow to the next line. Javascript doesn't equate the end of the line with the end of the statement.

var colorArr=["Red","Orange","Yellow",
    "Green","Blue","Purple"];

To understand the behavior you're seeing, note that this:

var test = -"test";
alert(test);

Outputs the NaN (not a number) that you're seeing. The parser is attempting to convert "Green" to a number -- so that it can evaluate what it assumes is a math expression (since it begins with +).

Sign up to request clarification or add additional context in comments.

2 Comments

Wow I'm dumb for not trying that. I was thinking it worked similar to putting the backslash to separate lines in document.write and stuff. Thanks!
@user1804208 instead say thank, you should upvote and accept the answer if it helps you.you have asked 16 question .even any single anwer haven't accept
7

+ "Green" is not a number.

Hence the NaN

Try just doing this:

var colorArr=["Red","Orange","Yellow",
              "Green","Blue","Purple"];

Sidebar:

NaN does not mean undefined:

NaN === undefined; // false

Comments

1

You can just press enter and go to the next line, no need for anything syntactically.

The reason it comes up as NaN is that it is trying to add a number with a string.

If you had: arr = ['whatever', 5 + 10]; it would output ['whatever', 15]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.