Skip to content Skip to sidebar Skip to footer

Javascript - Loop Through The Same Array More Than Once

How do I get the below for loop statement to go through my array more than once? var clients = new Array('client1', 'client2', 'client3', 'client4', 'client5'); var indexCounter;

Solution 1:

Put another loop around the loop.

for (var repeatCounter = 0; repeatCounter < 5; repeatCounter++) {
    for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
        holmesminutes = holmesminutes + 15;
        document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
    }
}

To stop all the loops when holmesminutes reaches 315:

for (var repeatCounter = 0; repeatCounter < 5 && holmesminutes < 315; repeatCounter++) {
    for (indexCounter = 0; indexCounter < clients.length && holmesminutes < 315; indexCounter++) {
        holmesminutes = holmesminutes + 15;
        document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
    }
}

As you see, you can put any condition you want in the test clause of for, it doesn't have to refer only to the iteration variable.

Solution 2:

Maybe try a while loop:

var clients = newArray("client1","client2","client3","client4","client5");
var indexCounter;
var holmesminutes =0;
_i= 0;

while (_i < 2) {
    for(indexCounter = 0; indexCounter<clients.length;indexCounter++)
     {
     holmesminutes = holmesminutes + 15;
     document.write(clients[indexCounter] + " testroom " +  holmesminutes + "<br>");
     _i++;
     }
}

Post a Comment for "Javascript - Loop Through The Same Array More Than Once"