JavaScript Tutorial/Statement/If

Материал из Web эксперт
Перейти к: навигация, поиск

Conditionals

The format of a simple if statement looks like the following:



   <source lang="javascript">

if (expression)

     statement;</source>
   
  

if...else

Syntax



   <source lang="javascript">

if(statement){

     code;
   }else(statement){
     code;
   }</source>
   
  

if...then...else...if

   <source lang="javascript">

<html> <head> <title>if...then...else...if</title> <script type="text/javascript"> var stateCode = "MO"; if (stateCode == "OR") {

  taxPercentage = 3.5;

} else if (stateCode == "CA") {

  taxPercentage = 5.0;

} else if (stateCode == "MO") {

  taxPercentage = 1.0;

} else {

  taxPercentage = 2.0;

} document.write(taxPercentage); </script> </head> <body> </body> </html></source>


Nested if statement

   <source lang="javascript">

<html> <head> <title>Nested if statement</title> <script> var temp = 0; temp = Math.floor(Math.random() * 100) + 1; alert ("It"s " + temp + " degrees outside. "); if (temp < 70){

 if (temp < 30){
   alert("< 30");
 } else {
   alert(" between 30 and 70");
 }

} else {

 if (temp > 85){
   alert("> 85");
 } else {
   alert("between 85 and 70");
 }

} </script> </head> <body>

Hit Reload to see another temperature

</body> </html></source>


Use if/else to check the returning value from a confirm dialog

   <source lang="javascript">

<html> <head> <title>A Simple Page</title> <script language="JavaScript">

</script> </head> <body> </body> </html></source>


Use if statement to check the returning value from a confirm dialog

   <source lang="javascript">

<html> <head> <title>A Simple Page</title> <script language="JavaScript">

</script> </head> <body> </body> </html></source>


Use if statement to compare the numbers

   <source lang="javascript">

<html> <head> <title>Use if statement to compare the numbers</title> <script> var temp = 0; var perfectTemp = 65;

temp = Math.floor(Math.random() * 100) + 1; alert ("It"s " + temp + " degrees outside. "); if (temp < perfectTemp){

 alert("Low!!");

} </script> </head> <body>

Hit Reload to see another temperature

</body> </html></source>