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!
asked Mar 7, 2013 at 18:19
netizen0911
4616 gold badges12 silver badges24 bronze badges
2 Answers 2
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 +
answered Mar 7, 2013 at 18:20
T.J. Crowder
1.1m201 gold badges2k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
tymeJV
While it doesn't apply to this specific array situation, nested for loops would be a good thing to read up on.
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++;
}
answered Mar 7, 2013 at 18:21
dave823
1,2112 gold badges16 silver badges32 bronze badges
Comments
lang-js
document.writein 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.forloop makes far more sense than awhile loop