在javascript中的一些選擇語句:
1、if語句 當指定條件爲true的時候,就執行該條件的代碼。
2、if...else...語句 當該語句指定條件爲true時則執行該代碼,如果當條件執行爲false時則執行其他代碼。
3、if...else if...else...語句 該語句是選擇多個代碼一起執行。
4、switch 語句 選擇多個代碼一起執行。
if語句
if(條件){
當條件爲true時執行的代碼;
}
例:
<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<20)
{
x="Good day";
}
document.getElementById("demo").innerHTML=x;
}
</script>
if...else...語句
if(條件){
當條件爲true時,執行代碼
}else{
當條件不爲true時(條件爲false),執行的代碼;
}
例:
<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>
if...else if...else...語句
if(條件1){
當條件1爲true時,執行代碼;
}else if(條件2){
當條件2爲true時,執行代碼;
}else{
當條件1和2 都不爲true時 ,執行的代碼;
}
例:
<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
document.getElementById("demo").innerHTML=x;
}
</script>