Javascript-多次遍历同一数组 [英] Javascript - loop through the same array more than once

查看:127
本文介绍了Javascript-多次遍历同一数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使下面的for循环语句多次遍历数组?

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>");
}

推荐答案

在循环中放置另一个循环.

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>");
    }
}

要在holmesminutes达到315时停止所有循环:

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>");
    }
}

如您所见,您可以将所需的任何条件放在for的test子句中,它不必仅引用迭代变量.

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.

这篇关于Javascript-多次遍历同一数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆