循环(迭代)代码块五次:
for (let i = 0; i < 5; i++) {
text += i + "<br>";
}
亲自试一试 »
循环(迭代)一个数组来收集汽车名称:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
for (let i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
亲自试一试 »
let i = 0
)。i
每次运行。i < cars.length
。下面有更多示例。
这个for
语句定义了一个代码块,只要满足条件就执行该代码块true
。
for (statement 1; statement 2; statement 3) {
code block to be executed
}
Parameter | Description |
statement 1 | Optional. Executed before the code block starts. Normally used to initialize a counter variable. To initiate multiple values, separate each value with a comma. This parameter can be omitted, but not the semicolon ";" |
statement 2 | Optional. The condition for running the code block. If it returns true the loop will start over again, otherwise the loop will end.This parameter can be omitted, but not the semicolon ";" |
statement 3 | Optional. Executed after the code block. Normally used to increment the counter variable. This parameter can be omitted (e.g. to increase/decrease values inside the loop) |
声明 | 描述 | |
休息 | 跳出循环 | |
继续 | 跳过循环中的值 | |
尽管 | 当条件为 true 时循环代码块 | |
做……同时 | 循环代码块一次,然后当条件为 true 时循环 | |
为了 | 当条件为 true 时循环代码块 | |
为了...的 | 循环任何可迭代的值 | |
为...在 | 循环对象的属性 |
在第一个参数中启动多个值:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
for (let i = 0, len = cars.length, text = ""; i < len; i++) {
text += cars[i] + "<br>";
}
亲自试一试 »
省略第一个参数(在循环开始之前设置值):
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
亲自试一试 »
使用continue
- 循环执行一段代码,但跳过值 3:
let text = "";
for (let i = 0; i < 5; i++) {
if (i == 3) continue;
text += i + "<br>";
}
亲自试一试 »
使用break
- 循环一个代码块,但在以下情况下退出循环i == 3
:
let text = "";
for (let i = 0; i < 5; i++) {
if (i == 3) break;
text += i + "<br>";
}
亲自试一试 »
省略第二个参数。
使用break
退出循环,否则循环将永远不会结束,并且您的浏览器将崩溃:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
for (let i = 0; ; i++) {
if (i == cars-length) break;
text += cars[i] + "<br>";
}
亲自试一试 »
按降序循环数组(负增量):
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
for (let i = cars.length - 1; i >= 0; i--) {
text += cars[i] + "<br>";
}
亲自试一试 »
省略最后一个参数,并增加循环内的值:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let i = 0;
let len = cars.length;
for (; i < len;) {
text += cars[i] + "<br>";
i++;
}
亲自试一试 »
循环 NodeList 并更改列表中所有 p 元素的颜色:
const myNodelist = document.getElementsByTagName("P");
for (let i = 0; i < myNodelist.length; i++) {
myNodelist[i].style.color = "blue";
}
亲自试一试 »
嵌套循环(循环内循环):
let text = "";
for (let = 0; i < 3; i++) {
text += i + "<br>";
for (let j = 10; j < 15; j++) {
text += j + "<br>";
}
}
亲自试一试 »
for
是 ECMAScript1 (ES1) 功能。
所有浏览器均完全支持 ES1 (JavaScript 1997):
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!