JavaScript If...Else 入門執行個體教程

來源:互聯網
上載者:User

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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.