[toc]
if 条件判断
if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
switch 语句 - 使用该语句来选择多个代码块之一来执行
if (condition1)
{
当条件 1 为 true 时执行的代码
}
else if (condition2)
{
当条件 2 为 true 时执行的代码
}
else
{
当条件 1 和 条件 2 都不为 true 时执行的代码
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>if判断</title>
</head>
<body>
<script>
a = 6;
if (a > 5) {
console.log('a大于5');
} else if ((a == 5)) {
console.log('a等于5');
} else {
console.log('a小于5');
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>单击按钮以显示基于时间的问候语:</p>
<button onclick="myFunction()">试一试</button>
<p id="demo"></p>
<script>
function myFunction() {
var greeting;
var time = new Date().getHours();
if (time < 10) {
greeting = "早上好";
} else if (time < 20) {
greeting = "中午好";
} else {
greeting = "晚上好";
}
document.getElementById("demo").innerHTML = greeting;
}
</script>
</body>
</html>
switch 基于不同条件执行不同动作
switch(表达式) {
case n:
代码块
break;
case n:
代码块
break;
default:
默认代码块
}
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var day;
switch (new Date().getDay()) {
case 0:
day = '周日';
break;
case 1:
day = '周一';
break;
case 2:
day = '周二';
break;
case 3:
day = '周三';
break;
case 4:
day = '周四';
break;
case 5:
day = '周五';
break;
case 6:
day = '周六';
}
document.getElementById('demo').innerHTML = '今天是' + day;
</script>
</body>
</html>