1

Please help. I'm just new at this. I've been trying to output 2 set of arrays with a loop and I couldn't seem to figure out.

Here's my code:

<script>
cars=["BMW","Volvo","Saab","Ford"];
type=["Sports","Luxury","Premium","Economy"];
var i=0;
var a=0;
while (cars[i])
{
document.write(cars[i] + " - " + type[a]"<br/>");
i++;
}
</script>

What I want to be the result is:

BMW - Sports
Volvo - Luxury
Saab - Premium
Ford - Economy

Thank you in advance!

2
  • Be careful to not use any form of document.write in a real application in a script block unless you're putting it inside a document ready handler like (using jQuery) $(function() { ... }). Writing from inside a script block directly will have performance penalties for most browsers as they have to stop rendering and recalculate all the html on the page. Commented Mar 7, 2013 at 18:25
  • Also, in this case a for loop makes far more sense than a while loop Commented Mar 7, 2013 at 18:25

2 Answers 2

4

As the entries you want to print out are at the same indexes in the arrays, just use i in both (and add he missing + after type[i]):

document.write(cars[i] + " - " + type[i] + "<br/>");
// Here ------------------------------^  ^-- this was the missing +
Sign up to request clarification or add additional context in comments.

1 Comment

While it doesn't apply to this specific array situation, nested for loops would be a good thing to read up on.
1

Just change the type[a] to type[i]. Since the arrays seem to be parallel, you can use the same index.

while (cars[i])
{
document.write(cars[i] + " - " + type[i] + "<br/>");
i++;
}

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.