JavaScript Switch 入門執行個體教程
有條件的聲明在JavaScript被用來執行不同的行動,根據不同的條件。
範例
switch語句
如何撰寫switch語句。
<html>
<body>
<script type="text/javascript">
var d = new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("<b>Finally Friday</b>");
break;
case 6:
document.write("<b>Super Saturday</b>");
break;
case 0:
document.write("<b>Sleepy Sunday</b>");
break;
default:
document.write("<b>I'm really looking forward to this weekend!</b>");
}
</script>
<p>This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>
</body>
</html>
的JavaScript switch語句
您應該使用switch語句如果你想選擇一個許多區塊的代碼將被處決。
文法
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different
這是它的原理就是:首先,我們有一個單一的表達語(最常見的一個變數) ,這是評價一次。價值的表達,然後與價值觀為每一個案例中的結構。如果有匹配的代碼塊與該案例的執行。利用休息,以防止代碼從運行到下一個案例自動運行。
例如
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>