更多例子
循环遍历数组的索引以从cars数组中收集汽车名称:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
尝试一下
上面的例子说明:
首先,我们在循环开始之前设置一个变量(var i = 0;)然后,我们定义循环运行的条件。只要变量小于数组的长度(为4),循环就会继续每次循环执行时,变量加1(i++),一旦变量不再小于4(数组的长度),条件为false,循环结束
在第一个参数中启动多个值:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i;
for (i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
尝试一下
省略第一个参数(循环开始前的设置值):
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 2;
var len = cars.length;
var text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
尝试一下
使用continue语句 - 循环遍历代码块,但跳过值“3”:
var text = ""
var i;
for (i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
text += "数字是: " + i + "<br>";
}
尝试一下
使用break语句 - 循环遍历代码块,但在变量i等于“3”时退出循环:
var text = ""
var i;
for (i = 0; i < 5; i++) {
if (i == 3) {
break;
}
text += "The number is " + i + "<br>";
}
尝试一下
省略第二个参数。在这个例子中,当i等于“3”时,我们也使用break语句来退出循环(如果省略第二个参数,你必须在循环中提供一个中断。否则循环将永远不会结束,你的浏览器将会崩溃):
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";
var i;
for (i = 0; ; i++) {
if (i == 3) {
break;
}
text += cars[i] + "<br>";
}
尝试一下
循环遍历数组的索引,按降序(负增量):
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var text = "";
var i;
for (i = cars.length - 1; i >= 0; i--) {
text += cars[i] + "<br>";
}
尝试一下
省略最后一个参数,并增加循环内的值:
var cars = ["BMW", "Volvo", "Saab", "Ford"];
var i = 0;
var len = cars.length;
for (; i < len;) {
text += cars[i] + "<br>";
i++;
}
尝试一下
循环遍历NodeList对象的节点并更改列表中所有<p>元素的背景颜色:
var myNodelist = document.getElementsByTagName("P");
var i;
for (i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.backgroundColor = "red";
}
尝试一下
嵌套循环的示例(循环内的循环):
var text = "";
var i, j;
for (i = 0; i < 3; i++) {
text += "<br>" + "i = " + i + ", j = ";
for (j = 10; j < 15; j++) {
document.getElementById("demo").innerHTML = text += j + " ";
}
}
尝试一下