let year =prompt('In which year was ECMAScript-2015 specification published?','');if (year ==2015) alert( 'You are right!' );
Boolean conversion
if statement 會將判斷式結果轉為布林值。
Value
Becomes…
0, null, undefined, NaN, ""
false
any other value
true
可以提前將判斷式存在變數中。
let cond = (year ==2015); // equality evaluates to true or falseif (cond) {...}
The “else” clause
當判斷式為錯誤,執行 else 的程式碼。
let year =prompt('In which year was the ECMAScript-2015 specification published?','');if (year ==2015) {alert( 'You guessed it right!' );} else {alert( 'How can you be so wrong?' ); // any value except 2015}
Several conditions: “else if”
let year =prompt('In which year was the ECMAScript-2015 specification published?','');if (year <2015) {alert( 'Too early...' );} elseif (year >2015) {alert( 'Too late' );} else {alert( 'Exactly!' );}
Conditional operator ‘?’
可以用 ternary operator ? 代替 if statement。用在返回一個值,而非執行一段程式。
let result = condition ? value1 : value2;let accessAllowed = (age >18) ?true:false; // recommend// the comparison operator "age > 18" executes first anyway// (no need to wrap it into parentheses)let accessAllowed = age >18?true:false;// the same 返回布林值可以不用 if statementlet accessAllowed = age >18;
let company =prompt('Which company created JavaScript?','');(company =='Netscape') ?alert('Right!') :alert('Wrong.'); // not recommend// samelet company =prompt('Which company created JavaScript?','');if (company =='Netscape') {alert('Right!');} else {alert('Wrong.');}