TypeScript 中的運算符

TypeScript 中的運算符

本文介紹了 TypeScript 中的運算符。

YouTube Video

TypeScript 中的運算符

TypeScript 中的運算符用於進行數值計算、值比較和邏輯運算。由於 TypeScript 使用的運算符與 JavaScript 類似,因此容易上手,但 TypeScript 通過類型安全允許進行更嚴格的操作。

主要的運算符如下:。

算術運算符

算術運算符用於數值計算。

運算符 描述 範例 結果
+ 加法 5 + 3 8
- 減法 5 - 3 2
* 乘法 5 * 3 15
/ 除法 5 / 2 2.5
% 取餘數 5 % 2 1
++ 增加 1(前置) let x = 5; ++x 6
-- 減少 1(前置) let x = 5; --x 4
 1let a = 10; // Initialize variable 'a' with the value 10
 2let b = 3;  // Initialize variable 'b' with the value 3
 3
 4// Perform and display arithmetic operations between 'a' and 'b'
 5console.log("Addition (a + b):      ", a + b); // 13
 6console.log("Subtraction (a - b):   ", a - b); // 7
 7console.log("Multiplication (a * b):", a * b); // 30
 8console.log("Division (a / b):      ", a / b); // 3.333...
 9console.log("Modulus (a % b):       ", a % b); // 1
10
11// Demonstrate post-increment operation on 'a'
12// Output the current value of 'a' (10), then increment
13console.log("Post-increment (a++):  ", a++);
14// Display the incremented value of 'a' (11)
15console.log("Value of 'a' after increment:", a);
16
17// Demonstrate pre-increment operation on 'a'
18// Increment 'a' first (12) then output
19console.log("Pre-increment (++a):   ", ++a);
20
21// Demonstrate post-decrement operation on 'a'
22// Output the current value of 'a' (12), then decrement
23console.log("Post-decrement (a--):  ", a--);
24// Display the decremented value of 'a' (11)
25console.log("Value of 'a' after decrement:", a);
26
27// Demonstrate pre-decrement operation on 'a'
28// Decrement 'a' first (10) then output
29console.log("Pre-decrement (--a):   ", --a);

賦值運算符

賦值運算符將右側的值賦予左側的變量。

運算符 描述 範例 結果
= 賦值 x = 10 x = 10
+= 加後賦值 x += 5 x = 15
-= 減後賦值 x -= 5 x = 5
*= 乘後賦值 x *= 2 x = 20
/= 除後賦值 x /= 2 x = 5
%= 取餘數後賦值 x %= 3 x = 1
1let z = 5;
2z += 3;
3console.log(z);  // Outputs: 8
4
5z *= 2;
6console.log(z);  // Outputs: 16

比較運算符

比較運算符用於比較值並返回truefalse

運算符 描述 示例 結果
== 等於(不比較類型) 5 == "5" true
=== 全等於(包含類型比較) 5 === "5" false
!= 不等於(不比較類型) 5 != "5" false
!== 全不等於(包含類型比較) 5 !== "5" true
> 大於 5 > 3 true
< 小於 5 < 3 false
>= 大於或等於 5 >= 5 true
<= 小於或等於 5 <= 3 false
1console.log('5 == "5"   :', 5 == "5");   // Outputs: true
2console.log('5 === "5"  :', 5 === "5");  // Outputs: false
3console.log('5 != "5"   :', 5 != "5");   // Outputs: false
4console.log('5 !== "5"  :', 5 !== "5");  // Outputs: true
5console.log('5 > 3      :', 5 > 3);      // Outputs: true
6console.log('5 < 3      :', 5 < 3);      // Outputs: false
7console.log('5 >= 5     :', 5 >= 5);     // Outputs: true
8console.log('5 <= 3     :', 5 <= 3);     // Outputs: false

邏輯運算符

邏輯運算符用於組合邏輯表達式。

運算符 描述 示例 結果
&& 邏輯與 true && false false
|| 邏輯或 true || false true
! 邏輯非 !true false
1console.log('true && false :', true && false);  // Outputs: false
2console.log('true || false :', true || false);  // Outputs: true
3console.log('!true         :', !true);          // Outputs: false

邏輯運算子的優先順序

在 TypeScript 中,邏輯運算子通常按照 NOTAND,最後是 OR 的順序進行評估。

NOT 擁有最高優先順序

NOT 是一元運算子,並且具有最高的優先順序。

1console.log(!true || false);  // false
AND 的優先順序高於 OR

AND 的優先順序高於 OR,因此會先對 AND 的部分進行計算。

1console.log(true || false && false);  // true

因此,會先計算 AND (&&) 部分,計算結果將傳遞給 OR (||)。

ANDOR 執行短路評估

在 TypeScript 中,ANDOR 會執行短路評估。如果結果已由左側的值決定,則不會計算右側的表達式。

1let a = false && console.log("This will not be printed");
2console.log(a);  // false
3
4let b = true || console.log("This will not be printed");
5console.log(b);  // true

在這兩種情況下,console.log() 都不會被執行。

明確定義優先順序

使用括號來明確分組表達式可以避免對優先順序的誤解。

1console.log(true || (false && false));  // true
自然語言與程式解讀的差異

使用邏輯運算子時,重要的是要注意自然語言中的模糊性。例如,在短語“a white dog or a cat”中,其可能意味著“a white dog or any cat”或“a white dog or a white cat”。在程式碼中,可以如下書寫:。

1if (isWhite && isDog || isCat) {
2    console.log(' "A white dog" or "a cat of any color" ');
3}
4
5if (isWhite && (isDog || isCat)) {
6    console.log(' "A white dog" or "a white cat" ');
7}

由於自然語言可能具有模糊性,因此在編寫程式和設計系統時需要謹慎。

位運算符

位運算符用於在位級別操作數字。

運算符 描述 示例 結果
& 邏輯與 5 & 1 1
` ` 邏輯或 5 | 1
^ 異或 (XOR) 5 ^ 1 4
~ 取反 (NOT) ~5 -6
<< 左移位 5 << 1 10
>> 右移位(有符號) 5 >> 1 2
>>> 右移位(無符號) 5 >>> 1 2
1console.log('5 & 1  :', 5 & 1);   // Outputs: 1  (AND operation)
2console.log('5 | 1  :', 5 | 1);   // Outputs: 5  (OR operation)
3console.log('5 ^ 1  :', 5 ^ 1);   // Outputs: 4  (XOR operation)
4console.log('~5     :', ~5);      // Outputs: -6 (NOT operation)
5console.log('5 << 1 :', 5 << 1);  // Outputs: 10 (Left shift operation)
6console.log('5 >> 1 :', 5 >> 1);  // Outputs: 2  (Right shift operation)
7console.log('5 >>> 1:', 5 >>> 1); // Outputs: 2  (Unsigned right shift operation)

三元運算符

三元運算符根據條件表達式的結果返回不同的值。

1let age = 20;
2let access = (age >= 18) ? "Allowed" : "Denied";
3console.log(access);  // Outputs: Allowed

型別運算子

TypeScript 的型別運算子包括以下內容:。

運算子 描述 範例 結果
typeof 返回變數的型別 typeof 123 "number"
instanceof 檢查一個物件是否屬於特定的類別 arr instanceof Array true
is 作為型別保護,檢查值是否為特定型別 value is string true or false
 1console.log(typeof "Hello");  // "string"
 2console.log(typeof 42);       // "number"
 3
 4let arr: number[] = [1, 2, 3];
 5console.log("arr instanceof Array : ", arr instanceof Array); // true
 6
 7// Example of Type Guard
 8function isString(value: any): value is string {
 9  return typeof value === "string";
10}
11
12let value: any = "Hello";
13if (isString(value)) {
14  console.log("Value is a string:", value);  // "Value is a string: Hello"
15}

型別運算子用於檢查值的型別或將其轉換為特定型別。

  • typeof 運算子返回變數的型別。
  • instanceof 運算子檢查物件是否屬於特定的類別。
  • is 運算子用於檢查值是否為特定型別。它是 TypeScript 型別保護的一部分。

總結

  • 算術運算符: 執行基本計算。
  • 賦值運算符: 賦值給變量。
  • 比較運算符: 比較值。
  • 邏輯運算符: 組合邏輯條件。
  • 位運算符: 執行位級操作。
  • 三元運算符: 根據條件返回值。
  • 型別運算子可以檢查值的型別。

在 TypeScript 中,這些運算符可用於高效地編寫複雜的計算和條件表達式。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video