JavaScript uses the if () {...} or else {...} To make conditional judgments. For example, depending on age, you can use the if statement to achieve the following:
[JavaScript]Plain Text view copy code ?
001002003004005006 |
var age =; if //if age >= 18 is true, Execute the IF statement block      ' adult ' " else { //Otherwise executes the ELSE statement block alert ( ' teenager ' } |
where else statements are optional. If the statement block contains only one statement, you can omit {}:
[JavaScript]Plain Text view copy code ?
001002003004005 |
var age =; if      alert ( ' adult ' else      alert ( ' teenager ' ); |
omitted The danger of {} is that if you later want to add some statements and forget to write {}, you change the if...else ... the semantics of, for example:
[JavaScript]Plain Text view copy code ?
001002003004005006 |
var age =; if &NBSP;&NBSP;&NBSP;&NBSP; alert ( ' adult ' else &NBSP;&NBSP;&NBSP;&NBSP; console.log ( //add a line of logs alert ( ' teenager ' Code class= "JavaScript plain"); //<-This line of statements is no longer within the control of else |
the Else clause of the above code is actually only responsible for executing console.log (' Age < 18 '); , the original alert (' teenager '); no longer belong to If...else ... control, and it executes every time.
Multi-line condition judgment
If you want to judge the condition more carefully, you can use multiple if...else ... Combination of:
[JavaScript]Plain Text view copy code ?
001002003004005006007008 |
var age = 3;
if (age >= 18) {
alert(
‘adult‘
);
}
else if (age >= 6) {
alert(
‘teenager‘
);
}
else {
alert(
‘kid‘
);
}
|
What if the conditional judgment statement result of the IF is not true or false ? For example:
[JavaScript]Plain Text view copy code ?
001002003004 |
var s = ' 123 ' if (s.length) { //condition evaluates to 3 &NBSP;&NBSP;&NBSP;&NBSP; // } |
JavaScript treats null,undefined,0,NaN, and empty string ' ' as false, All other values are treated as true, so the result of the above code condition is true.
http://www.sodu666.com/HaiZeiZhiShenJiJinHua/
http://www.ququer.org/
JavaScript Concise tutorial (5) Conditional judgment