Alison1988 Alison1988 - 7 months ago 11
Javascript Question

How do I make an array keep going?

I want to make an array keep on going as opposed to stopping on the last object, if I have sorted its elements how do I make it keep going ?

window.onload=nextcity;

var c = new Array();
c[0] = {cName:"Dresden"};
c[1] = {cName:"Belin"};
c[2] = {cName:"Frankfurt"};
c[3] = {cName:"Koln"};
c[4] = {cName:"Dusseldorf"};
c[5] = {cName:"Leipzig"};

c.sort();

var Citynum = 0;

function nextcity () {
document.getElementById('cityoptions').innerHTML=c[Citynum].cName;
Citynum ++;
}


To explain better, when a button is clicked I want the writing to change to a city name i.e. it would look something like this

<
DRESDEN
>


and when the arrow is clicked it will show a different name I don't want it to stop I want it to keep going.

Answer

You could reset the Citynum counter to 0 once it reaches the size of c, making the list repeat:

function nextcity () {
  document.getElementById('cityoptions').innerHTML=c[Citynum].cName;
  Citynum ++;
  if (Citynum >= c.length)
    Citynum = 0;
}