user3483571 user3483571 - 1 year ago 62
HTML Question

Javascript While Looping Through Array And Outputting in .innerhtml

I'm brand new to Javascript and teaching myself. I'm trying to setup a function that will write each of the elements of the array

with a space between the elements.

I have it working so that when I use
.innerHTML=AmericanCars[Index Position]
plus a non-breaking space, I can write one element of the array. Now I'm trying to loop through it with a
loop, but I just get an output of "undefined."

How can I get
to write out each of the elements of an array with a space between them? Is there a method that is simpler than using the While loop or is my While loop just formatted wrong.


<script language="javascript" type="text/javascript">
var AmericanCars=["Chevy", "Ford", "Dodge"];
var JapaneseCars=["Honda", "Toyota", "Subaru"];
var FavoriteCars=[];

function ListAmericanCars() {

var arraycounter = 0;

/* Use array counter to set the value that is displayed in innerHTML's square [] brackets */
while (arraycounter <= AmericanCars.length) {

document.getElementById('content').innerHTML = AmericanCars[arraycounter] + "&nbsp ";

<p> What Are Your Favorite American Cars? Answer:
<span id="content">______________

<button onclick="ListAmericanCars()">
American Cars Function

Answer Source

Arrays are 0-based. Change it to less than or else the last element will print undefined.

while (arraycounter < AmericanCars.length) {

Additionally, you could just do:

document.getElementById('content').innerHTML = AmericanCars.join('&nbsp');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download