Use of If statements in JavaScript _javascript tips

Source: Internet
Author: User
Some of the selection statements in JavaScript:


1, if statement the code that executes the condition when the specified condition is true.


2, If...else ... Statement executes the code when the statement specifies that the condition is true, and executes other code if the condition is executed as false.


3, If...else if...else ... Statement is to select multiple code to execute together.


4, the switch statement selects multiple code to execute together.





If statement


if (condition) {


code that executes when the condition is true;


}





Example:


Copy Code code as follows:

<script>
function MyFunction ()
{
var x= "";
var time=new Date (). GetHours ();
if (time<20)
{
x= "Good Day";
}
document.getElementById ("Demo"). Innerhtml=x;
}
</script>



If...else ... Statement


if (condition) {


executes code when the condition is true


}else{


code to execute when the condition is not true (the condition is false);


}


Example:


Copy Code code as follows:

<script>
function MyFunction ()
{
var x= "";
var time=new Date (). GetHours ();
if (time<20)
{
x= "Good Day";
}
Else
{
x= "Good evening";
}
document.getElementById ("Demo"). Innerhtml=x;
}
</script>



if...else If...else ... Statement


if (condition 1) {


executes the code when the condition 1 is true;


}else if (condition 2) {


executes the code when the condition 2 is true;


}else{


code to execute when both conditions 1 and 2 are not true;


}


Example:


Copy Code code as follows:
<script>
Function MyFunction ()
{
var x=" ";
var time=new Date (). GetHours ();
if (time<10)
{
x= "Good Morning";
}
Else if (time<20)
{
x= "Good Day";
}
Else
{
x= "good evening";
}
document.getElementById ("Demo"). Innerhtml=x;
}
</script>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.