1. 循环
1.0 断点调试
1.1 for
<!DOCTYPE html
>
<html lang
="en">
<head
>
<meta charset
="UTF-8">
<meta name
="viewport" content
="width=device-width, initial-scale=1.0">
<meta http
-equiv
="X-UA-Compatible" content
="ie=edge">
<title
>Document
</title
>
<script
>
for (var i
= 1; i
<= 100; i
++) {
console
.log('你好吗');
}
</script
>
</head
>
<body
>
</body
>
</html
>
执行过程
<script
>
for (var i
= 1; i
<= 100; i
++) {
console
.log('你好吗');
}
</script
>
一些例子
<script
>
var num
= prompt('请您输入次数');
for (var i
= 1; i
<= num
; i
++) {
console
.log('媳妇我错了');
}
</script
>
<script
>
var sum
= 0;
for (var i
= 1; i
<= 100; i
++) {
sum
+= i
;
}
console
.log(sum
);
</script
>
求学生成绩案例
<script
>
var num
= prompt('请输入班级的总人数:');
var sum
= 0;
var average
= 0;
for (var i
= 1; i
<= num
; i
++) {
var score
= prompt('请您输入第' + i
+ '个学生成绩');
sum
= sum
+ parseFloat(score
);
}
average
= sum
/ num
;
alert('班级总的成绩是' + sum
);
alert('班级平均分是:' + average
);
</script
>
打印星星案例
<script
>
var num
= prompt('请输入星星的个数');
var str
= '';
for (var i
= 1; i
<= num
; i
++) {
str
= str
+ '★'
}
console
.log(str
);
</script
>
<script
>
var str
= '';
for (var i
= 1; i
<= 5; i
++) {
for (var j
= 1; j
<= 5; j
++) {
str
= str
+ '★';
}
str
= str
+ '\n';
}
console
.log(str
);
</script
>
<script
>
var rows
= prompt('请您输入行数:');
var cols
= prompt('请您输入列数:');
var str
= '';
for (var i
= 1; i
<= rows
; i
++) {
for (var j
= 1; j
<= cols
; j
++) {
str
= str
+ '★';
}
str
+= '\n';
}
console
.log(str
);
</script
>
<script
>
var str
= '';
for (var i
= 1; i
<= 10; i
++) {
for (var j
= i
; j
<= 10; j
++) {
str
= str
+ '★';
}
str
+= '\n';
}
console
.log(str
);
</script
>
九九乘法表案例
<script
>
var str
= '';
for (var i
= 1; i
<= 9; i
++) {
for (var j
= 1; j
<= i
; j
++) {
str
+= j
+ '×' + i
+ '=' + i
* j
+ '\t';
}
str
+= '\n';
}
console
.log(str
);
</script
>
1.2 while
<script
>
var num
= 1;
while (num
<= 100) {
console
.log('好啊有');
num
++;
}
</script
>
案例
<script
>
var i
= 1;
while (i
<= 100) {
console
.log('这个人今年' + i
+ '岁了');
i
++;
}
var sum
= 0;
var j
= 1;
while (j
<= 100) {
sum
+= j
;
j
++
}
console
.log(sum
);
var message
= prompt('你爱我吗?');
while (message
!== '我爱你') {
message
= prompt('你爱我吗?');
}
alert('我也爱你啊!');
</script
>
1.3 do while
<script
>
do {
} while (条件表达式
)
var i
= 1;
do {
console
.log('how are you?');
i
++;
} while (i
<= 100)
</script
>
案例
<script
>
var i
= 1;
do {
console
.log('这个人今年' + i
+ '岁了');
i
++;
} while (i
<= 100)
var sum
= 0;
var j
= 1;
do {
sum
+= j
;
j
++;
} while (j
<= 100)
console
.log(sum
);
do {
var message
= prompt('你爱我吗?');
} while (message
!== '我爱你')
alert('我也爱你啊');
</script
>
1.4 continue
<script
>
for (var i
= 1; i
<= 5; i
++) {
if (i
== 3) {
continue;
}
console
.log('我正在吃第' + i
+ '个包子');
}
var sum
= 0;
for (var i
= 1; i
<= 100; i
++) {
if (i
% 7 == 0) {
continue;
}
sum
+= i
;
}
console
.log(sum
);
</script
>
1.5 break
<script
>
for (var i
= 1; i
<= 5; i
++) {
if (i
== 3) {
break;
}
console
.log('我正在吃第' + i
+ '个包子');
}
</script
>
参考: 视频 代码
转载请注明原文地址:https://ipadbbs.8miu.com/read-54271.html