JS中的条件语句一般用在针对不同的条件来执行不同的动作。
假设语句
在写代码时经常会遇到想根据不同的判断来执行不同的动作。你可以用假设语句来做到这点。
在JS中有以下一些假设(条件)语句:
- 这条语句一般是在代码在只有一个状态为真的情况下就执行的时候使用
- 两个状态,一种为真,还有种不为真,分别执行不同动作。
- 你想在多个条件中选择一个或几个去执行,就用这个
- 在许多条件中选择一个去执行,用这个
if语句
你应该在代码在只有一个状态为真的情况下就执行的时候使用这条语句
语法
if (condition) { code to be executed if condition is true }
|
注意if语句应该用小写,使用大写的话会引起JS错误
例子1
<script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10
var d=new Date() var time=d.getHours() if (time<10) { document.write("<b>Good morning</b>") } </script>
|
例子2
<script type="text/javascript"> //Write "Lunch-time!" if the time is 11
var d=new Date() var time=d.getHours() if (time==11) { document.write("<b>Lunch-time!</b>") } </script>
|
注意:要比较变量你就必须使用两个等号标记(==)!
注意这里没有使用else。你只是让代码当条件为真时就执行。
If...else 语句
如果你想条件为真时运行一些代码而不为真时运行另一些代码,就用if...else语句
语法
if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true }
|
例子
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10) { document.write("Good morning!") }
else { document.write("Good day!") }
</script>
|
If...else if...else 语法
如果你想在几种条件中选择一种去执行,那就应该用if....else if...else语句
语法
if (condition1) { code to be executed if condition1 is true }
else if (condition2) { code to be executed if condition2 is true }
else { code to be executed if condition1 and condition2 are not true }
|
Example
例子
<script type="text/javascript"> var d = new Date() var time = d.getHours()
if (time<10) { document.write("<b>Good morning</b>") }
else if (time>10 && time<16) { document.write("<b>Good day</b>") }
else { document.write("<b>Hello World!</b>") }
</script>
|
|