js的三种for循环:(for)、(for in)、(for of)

for 循环

通用循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>点击按钮循环代码块 5 次。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>

<script>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
</head>

<body>
<p>点击按钮循环代码块 5 次。</p>
<button onclick="test()">点我</button>
<p id="demo"></p>

<script>
var text = "";

function test() {
for (let i = 0; i < 5; i++) {
text += `The number is ${i}<br>`;
}
/* // 使用 continue 语句,在i等于3时跳过当前循环
for (i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
text += `The number is ${i}<br>`;
}
*/
/* // 使用 break 语句 在i等于3时跳出当前循环
for (i = 0; i < 5; i++) {
if (i == 3) {
break;
}
text += `The number is ${i}<br>`;
}
*/
document.getElementById("demo").innerHTML = text;
}

</script>

</body>

</html>

结果:
js的三种for循环:(for)、(for in)、(for of)

for in 循环

用于循环对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
</head>

<body>
<p>点击按钮循环对象属性。</p>
<button onclick="test()">点我</button>
<p id="demo"></p>

<script>
var person = {
name: "quanyi",
position: "frontend devloper",
age: 25
};

var text = "";
function test() {
for (let x in person) {
text += person[x] + " <br>";
console.log(x);
}
document.getElementById("demo").innerHTML = text;
}

</script>

</body>

</html>

js的三种for循环:(for)、(for in)、(for of)

for of 循环

遍历字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script>
var string="why give up treatment";
for(let i of string){
console.log(i);
}
</script>
</body>
</html>

js的三种for循环:(for)、(for in)、(for of)


js的三种for循环:(for)、(for in)、(for of)
https://github.com/chergn/chergn.github.io/7aa8c8161be4/
作者
全易
发布于
2024年3月28日
许可协议