May 06, 2021 JavaScript
1. JavaScript if... Else statement
5. Javascript tri-operation (triple operation) statement
Conditional statements are used to perform different actions based on different conditions.
Often when you write code, you always need to perform different actions for different decisions. You can use conditional statements in your code to accomplish the task.
In JavaScript, we can use the following conditional statements:
The statement executes the code only if the specified condition is true.
Use a small-ced if. Using capital letters (IF) generates JavaScript errors!
When the time is less than 20:00, the greeting "Good day" is generated:
Note that in this syntax, there is no .. e lse..。 You have told the browser to execute the code only if the specified condition is true.
Please use if.... The else statement executes code when the condition is true and other code when the condition is false.
When the time is less than 20:00, the greeting "Good day" is generated, otherwise the greeting "Good evening" is generated.
The result of x is:
Tip: In this site's programming battle, you can practice how to use JavaScript's if statement!
5 > 3 ? alert("5大于3") : alert("5小于3");
Note: if...
The difference between else and tri-eye operation is summed up in one sentence: tri-eye operation has a return value, if else does not return a value
Example 1:
var n=1;
if(n>1){
n=0;
}else{
n++;
}
console.log(n);
#输出结果:2
var n=1;
n = n>1?0 : n++;
console.log(n);
#输出结果为:1
Example 2:
var n=1;
if(n>1){
n=0;
}else{
++n;
}
console.log(n);
#输出结果:2
var n=1;
n = n>1?0 : ++n;
console.log(n);
#输出结果为:2
Use if.... e lse if... The else statement selects one of several blocks of code to execute.
If the time is less than 10:00, the greeting "Good morning" is generated, and if the time is greater than 10:00 is less than 20:00, the greeting "Good day" is generated, otherwise the greeting "Good evening" is generated:
The result of x is:
Tip: When using if and else if statements, you need to pay attention to the order in which the code is executed, please refer to this site's JavaScript Programming Practice!
Random links
This example demonstrates a link that takes you to a different place when you click on it.
Each opportunity has a 50% probability.
JavaScript Standard Reference Manual: Javascript if conditions