JavaScript If...Else 入門執行個體教程
有條件的聲明在JavaScript被用來執行不同的行動,根據不同的條件。
條件陳述式
往往當你寫代碼,您要執行不同的行動不同的決定。您可以使用條件陳述式中的代碼來做到這一點。
在JavaScript中,我們有以下條件陳述式:
如果聲明-使用此聲明如果你想執行一些代碼只有在指定的條件是真的
如果... else語句-使用此聲明如果你想執行一些代碼,如果條件是真實的,如果另一代碼的條件是假的
如果別人...如果.... else語句-使用此聲明如果你想選擇一個許多區塊的代碼將被處決
switch語句-使用此聲明如果你想選擇一個許多區塊的代碼將被處決
如果聲明
您應該使用if語句如果你想執行一些代碼只有在指定的條件是真實的。
文法
if (condition)
{
code to be executed if condition is true
}
請注意,如果是寫字母。用大寫字母( IF )的會產生一個JavaScript錯誤! 範例1<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10var d=new Date();
var time=d.getHours();
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>if... else語句如果你想執行一些代碼,如果一個條件是真實的,如果另一代碼的條件是不正確的,如果使用.... 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 Statement您應該使用的,如果....如果別人... 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
}<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>