JavaScript if...Else 语句

更新时间:2020-06-21 11:51
条件语句

通常在写代码时,您总是需要为不同的决定来执行不同的动作。您可以在代码中使用条件语句来完成该任务。

在 JavaScript 中,我们可使用以下条件语句:

  • if 语句 - 只有当指定条件为 true 时,使用该语句来执行代码
  • if...else 语句 - 当条件为 true 时执行代码,当条件为 false 时执行其他代码
  • if...else if....else 语句- 使用该语句来选择多个代码块之一来执行
  • switch 语句 - 使用该语句来选择多个代码块之一来执行

if 语句

只有当指定条件为 true 时,该语句才会执行代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>95知识库(995w.com)</title>
</head>
<body>

<p>如果时间早于 20:00,会获得问候 "Good day"。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
	var x="";
	var time=new Date().getHours();
	if (time<20){
		x="Good day";
    }
	document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

尝试一下>>


if...else 语句

请使用 if....else 语句在条件为 true 时执行代码,在条件为 false 时执行其他代码。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>95知识库(995w.com)</title>
</head>
<body>

<p>点击这个按钮,获得基于时间的问候。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
	var x="";
	var time=new Date().getHours();
	if (time<20){
	 	x="Good day";
     }
    else{
 		x="Good evening";
     }
	document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

尝试一下>>


if...else if...else 语句

使用 if....else if...else 语句来选择多个代码块之一来执行。

<html>
<head>
<meta charset="utf-8">
<title>95知识库(995w.com)</title>
</head>
<body>

<script type="text/javascript">
var d = new Date();
var time = d.getHours();
if (time<10)
{
	document.write("<b>早上好</b>");
}
else if (time>=10 && time<20)
{
	document.write("<b>今天好</b>");
}
else
{
	document.write("<b>晚上好!</b>");
}
</script>
<p>
这个例子演示了 if..else if...else 语句。
</p>

</body>
</html>

尝试一下>>