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 false
if (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...' );
} else if (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 statement
let accessAllowed = age > 18;
Multiple ‘?’
let age = prompt('age?', 18);
let message = (age < 3) ? 'Hi, baby!' :
(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';
alert( message );
// same
if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
}
Non-traditional use of ‘?’
ternary operator ? 用在返回一個值,而非執行一段程式。
let company = prompt('Which company created JavaScript?', '');
(company == 'Netscape') ?
alert('Right!') : alert('Wrong.'); // not recommend
// same
let company = prompt('Which company created JavaScript?', '');
if (company == 'Netscape') {
alert('Right!');
} else {
alert('Wrong.');
}