学习目标:
掌握js循环语句
学习内容:
js循环中有for、while、do while
三种循环大部分情况下可以互相替代使用。
for:多用于计数,跟数字有关的我们基本使用for循环。
根据输入的行列打印星星:
<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>
打印了5行6列的星星:
while:可以做更复杂的条件筛选,比for更加灵活一些 与do while不同,先判断后执行。
<script>
// 1.while循环语法结构 while 当。。。的时候
// while(条件表达式) {
// 循环体
// }
// 2.执行思路 当条件表达式结果为true 则执行循环体 否则 退出循环
// 3.代码验证
var num = 1;
while (num <= 100) {
console.log('好啊有');
num++;
}
// while循环案例
var sum = 0;
var j = 1;
while (j <= 100 ) {
sum += j;
j++
}
console.log(sum);
var message = prompt('你爱我吗?');
while (message !== '我爱你') {
message = prompt('你爱我吗?');
}
alert('我也爱你啊!');
</script>
do while:可以做更复杂的条件筛选,比for更加灵活一些 与4while不同,先执行一次后判断,至少会执行一次。
<script>
// 格式:
do {
//循环体
}while (条件表达式)
// 先执行一次循环体 ,再判断条件
var i = 1;
do {
console.log('how are you?');
i++
}while (i <= 100)
// 案例:
do {
var message = prompt('你爱我吗?')
}while (message !== '我爱你')
alert('我也爱你啊');
</script>
学习时间:
2021年12月27日
周一上午9点-10点