1. 指數運算符 **
(1). 用法:x**n
- x表示需要指數運算的數值,n表示n次方。
如:let num = 2 ** 3;
console.log(num); // 8, 2的3次方。
- 若有數值包含負號,則必須把該數值用小括號()括起來后,才能執行操作。不然,會報語法錯誤。
如:let num = -2 ** 3;// Uncaught SyntaxError
又如:let num = (-2) ** 3;
console.log(result); // -8
- 只有number與bigint兩種數值類型可以使用指數運算符 **。
2. if 語句
(1). if 語法:
- 單一語句的語法:
if (條件)
statement;
如:let a = 2;
if (a < 3)
console.log(a); // 2
- 多語句的語法:
if (條件) {
statement 1;
statement 2;
};
如:let a = 2;
if (a < 3) {
a += 1;
console.log(a);
}; // 3
- 嵌套的if語句:
if (條件1) {
if (條件2) {
statement;
}};
如:let a = 2;
if (a < 3) {
if (a !== 1){
console.log(a);
}}; // 2
3. if...else 語句
(1). if...else語法:
if (條件) {
statement;
} else {
statement;
}
如:let a = 2;
if (a > 3) {
console.log(a);
} else {
console.log(a + 1);
}; // 3
4. if...else if...else 語句
(1). if...else if...else 語法:
if (條件1) {
statement;
} else if (條件2) {
statement;
} else {
statement;
};
如:let a = 2;
if (a > 3) {
console.log(a);
} else if (a === 2) {
console.log("a = 2");
} else {
console.log(a + 1);
}; // "a = 2"
5. 三元運算符
(1). 語法:
- 執行單個語句:
condition ? expression if true : expression if false;
即:條件 ?滿足的結果 :不滿足的結果;
如:let a = 2, b;
b = a > 3 ? 'a大於3' :'a小於,或等於3';
console.log(b); // 'a小於,或等於3'
- 執行多個語句:
如:let a = 2, b;
b = a > 3 ? (alert('呦呵'), '數字大於3呐') : (alert(‘太小啦’), '才小於或等於3');
console.log(b); // '才小於或等於3'
- 嵌套的語句:
如:
let a = 2, b;
b = a > 3 ? '數字大於3呐' : a > 0 ? '至少大於0' :'哎,數字太小啦';
console.log(b); // '至少大於0'