條件敘述與迴圈

條件敘述

if/else 敘述區塊

if/else 敘述區塊結構

<SCRIPT language="JavaScript">
<!--
    var boats=3;
    if (boats==3)
    {
        window.alert("You have the right number of boats");
    }
    else
    {
        window.alert("You do not have the right number of boats");
    }
//-->
</SCRIPT>

巢狀區塊

<SCRIPT language="JavaScript">
<!--
    var have_cookbook="yes";
    var meatloaf_recipe="yes";

    if (have_cookbook=="yes")
    {
        if (meatloaf_recipe=="yes")
        {
            window.alert("Recipe found");
        }
        else
        {
            window.alert("Have the book, but no recipe");
        }
    }
    else
    {
        window.alert("You need a cookbook");
    }
//-->
</SCRIPT>

複雜的比較

<SCRIPT language="JavaScript">
<!--
    var num1=9;
    if ((num1>2)&&(num1<11)||(num1==20))
    {
        window.alert("Cool number");
    }
    else
    {
        window.alert("Not a cool number");
    }
//-->
</SCRIPT>

switch 敘述


<SCRIPT language="JavaScript">
<!--
    var name="Fred";
    switch (name)
    {
    case "George" :
        window.alert("George is an Ok name");
        break;
    case "Fred" :
        window.alert("Fred is the coolest name");
        window.alert("Hi there, Fred!");
        break;
    case default :
        window.alert("Interesting name you have there");
    }
//-->
</SCRIPT>

迴圈

for 敘述

for 迴圈結構

<html>
<head>
<title>Looping</title>
</head>
<body>
Get ready for some repeated text.
<SCRIPT language="JavaScript">
<!--
    for (count=1;count<11;count+=1)
    {
        document.write("I am part of a loop!<br>");
    }
//-->
</SCRIPT>
<p>
Now we are back to the plain HTML code.
</body>
</html>

巢狀區塊

<html>
<head>
<title>Nesting and Looping</title>
</head>
<body>
Get ready for some repeated text.
<SCRIPT language="JavaScript">
<!--
    for (count=1;count<11;count+=1)
    {
        document.write(count+". I am part of a loop!<br>");
        for (nestcount=1;nestcount<3;nestcount+=1)
        {
            document.write("I keep interrupting in pairs!<br>");
        }
    }
//-->
</SCRIPT>
<p>
Now we are back to the plain HTML code.
</body>
</html>

while 敘述


<html>
<head>
<title>Looping</title>
</head>
<body>
Get ready for some repeated text.
<SCRIPT language="JavaScript">
<!--
    var count=1;
    while (count<11)
    {
        document.write(count+". I am part of a loop!<br>");
        count+=1;
    }
//-->
</SCRIPT>
<p>
Now we are back to the plain HTML code.
</body>
</html>