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>