js所有循环语句以及流程控制

1.if else语句


如果表达式结果为真,则输出语句1.
如果为假则跳到else语句,输出语句2.

var num = parseInt( Math.random()*99 + 1 );	//使用random()函数生成一个随机数
//console.log( num );
if ( num % 2 == 0){	//判断变量num是否为偶数
    console.log( num + "是偶数。");
}

if ( num % 2 == 0)	//判断变量num是否为偶数
    console.log( num + "是偶数。");
var num = parseInt( Math.random()*99 + 1 );	//使用random()函数生成一个随机数
//console.log( num );
if ( num % 2 == 0){	//判断变量num是否为偶数
    console.log( num + "是偶数。");
}
else {
    console.log( num + "是奇数。");
}
var num = parseInt( Math.random()*99 + 1 );	//使用random()函数生成一个1到100的随机数
if ( num < 60 ){
    console.log( "不及格" );
}
else{
	if ( num < 70 ){
		console.log( "及格" );
	}
	else {
		if ( num < 85 ){
			console.log( "良好" );
		}
		else {
			console.log( "优秀" );
		}
	}
}

2.switch语句

swith语句专门用来设计多分支条件结构。与else if语句相比,switch结构更简洁,执行效率更高。

在这里插入图片描述

<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<script>
var id = 1;
switch ( id ) {
    case 1:
        console.log( "普通会员" );
        break;
    case 2:
        console.log( "VIP会员" );
        break;
    case 3:
        console.log( "管理员" );
        break;
    default:
        console.log( "游客" );
}

</script>
</body>
</html>

3.循环语句while

在这里插入图片描述

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<script>

var n = 1;	//声明并初始化循环变量
while(n <= 100){	//循环条件
    n ++ ;	//递增循环变量
	if( n%2 == 0) document.write( n + " " );	//执行循环操作
}

</script>
</body>
</html>

4.for语句

在这里插入图片描述
for语句是一种更简洁高效的语句,例题如下

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<script>

for(var n =1; n<=100; n++){
    if( n%2 == 0) document.write( n + " " );	//执行循环操作
}

</script>
</body>
</html>

这时你会发现,使用for语句一行代码即可,非常的简单和便捷

5.流程控制

(1).break语句

break语句能够结束当前的for,while,或swich语句的执行:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<script>

for(i in document){
    if(i.toString() == "bgColor"){
        document.write("document." + i + "=" + document[i] + "<br />");
        break;
    }
}

</script>
</body>
</html>

(2)continue语句

continue语句用在循环结构内,用于跳过本次循环中剩余的代码。并在表达式为真时,继续执行下一次循环。它可以接受一个可选的标签名,来跳出本次的循环语句。

在这里插入图片描述

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<script>

var a = [1, "hi", 2, "good", "4", , "" , 3, 4],	//定义并初始化数组a
    b = [], j = 0;	//定义数组b和变量j
for(var i in a){	//遍历数组a
    if(typeof a[i] == "string") // 如果为字符串,则返回继续下一次循环
        continue;
    b[j ++ ] = a[i];	//把数字寄存到数组b
}
document.write(b);	//返回1,2,3,4

</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值