Javascript - loop through the same array more than once

筅森魡賤 提交于 2020-01-06 19:48:09

问题


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;
var holmesminutes = 0;
for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
    holmesminutes = holmesminutes + 15;
    document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}

回答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.




回答2:


Maybe try a while loop:

var clients = new Array("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++;
     }
}


来源:https://stackoverflow.com/questions/21205449/javascript-loop-through-the-same-array-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!