TypeScript 重複語句
本文介紹了 TypeScript 中的重複語句。
YouTube Video
TypeScript 中的 for 語句
TypeScript 中的 for 語句是一種用於執行重複操作的基本迴圈結構。在一個 for 迴圈中,可以根據指定的次數或條件重複執行相同的代碼塊。
基本語法
1for (initialization; condition; update) {
2 // Code to execute repeatedly while the condition is true
3}- 初始化(
initialization):在開始循環之前只執行一次的部分。初始化變量,例如循環計數器。 - 條件(
condition):決定是否繼續循環的條件。如果為true,循環繼續;如果為false,則結束。 - 更新(
update):在每次循環結束時執行以更新循環計數器。
範例 1:基本的 for 迴圈
以下範例將按順序輸出數字從 0 到 4。
1for (let i = 0; i < 5; i++) {
2 console.log("The value of i is: " + i);
3}
4// Outputs:
5// The value of i is: 0
6// The value of i is: 1
7// The value of i is: 2
8// The value of i is: 3
9// The value of i is: 4
範例 2:帶有陣列的 for 迴圈
您也可以使用 for 迴圈按順序處理陣列的元素。
1let fruits: string[] = ["apple", "banana", "cherry"];
2
3for (let i = 0; i < fruits.length; i++) {
4 console.log("Fruit: " + fruits[i]);
5}
6// Outputs:
7// Fruit: apple
8// Fruit: banana
9// Fruit: cherry
範例 3:for-in 迴圈
for-in 迴圈用於依次遍歷對象的屬性或陣列的索引。
1let car = { brand: "Toyota", model: "Corolla", year: 2020 };
2
3for (let key in car) {
4 console.log(key + ": " + car[key]);
5}
6// Outputs:
7// brand: Toyota
8// model: Corolla
9// year: 2020
範例 4:for-of 迴圈
for-of 迴圈用於從可迭代對象(例如陣列或字符串)中按順序獲取每個元素的值。
1let colors: string[] = ["red", "green", "blue"];
2
3for (let color of colors) {
4 console.log("Color: " + color);
5}
6// Outputs:
7// Color: red
8// Color: green
9// Color: blue
範例 5:嵌套的 for 迴圈
還可以在一個 for 迴圈內部使用另一個 for 迴圈,這稱為嵌套迴圈。這使您可以創建雙重迴圈等功能。
1for (let i = 0; i < 3; i++) {
2 console.log("Outer loop i: " + i);
3 for (let j = 0; j < 2; j++) {
4 console.log(" Inner loop j: " + j);
5 }
6}
7// Outputs:
8// Outer loop i: 0
9// Inner loop j: 0
10// Inner loop j: 1
11// Outer loop i: 1
12// Inner loop j: 0
13// Inner loop j: 1
14// Outer loop i: 2
15// Inner loop j: 0
16// Inner loop j: 1
總結
for語句基於指定的次數或條件執行重複的處理。for-in用於檢索對象的屬性或陣列的索引。for-of用於從可迭代對象(例如陣列)中檢索元素的值。- 嵌套的
for迴圈也可以實現複雜的重複處理。
TypeScript 中的 for 語句提供了強大而靈活的重複處理功能,類似於其他迴圈。
TypeScript 中的 while 語句
在 TypeScript 中,while 語句是一種循環結構,當指定的條件為 true 時執行重複的處理過程。與 for 循環相似,while 循環適用於迭代次數不確定或需要根據條件來控制重複的情況。
基本語法
1while (condition) {
2 // Code to execute repeatedly while the condition is true
3}- 條件:決定循環執行的條件。只要條件為
true,循環將繼續執行;當條件變為false時,循環終止。
範例 1:基本的 while 循環
在以下範例中,當 i 小於 5 時,將持續輸出 i 的值。
1let i: number = 0;
2
3while (i < 5) {
4 console.log("The value of i is: " + i);
5 i++;
6}
7// Outputs:
8// The value of i is: 0
9// The value of i is: 1
10// The value of i is: 2
11// The value of i is: 3
12// The value of i is: 4
在此範例中,當 i 變為 5 或大於 5 時,循環終止,因為條件變為 false。
範例 2:無限循環範例
如果 while 循環中的條件始終為 true,則可能成為無限循環。這通常會導致程式無法按預期停止,因此需要謹慎處理。
1let x: number = 0;
2
3while (true) {
4 console.log("The value of x is: " + x);
5 x++;
6 if (x >= 5) {
7 break; // Exit the loop when the condition is met
8 }
9}
10// Outputs:
11// The value of x is: 0
12// The value of x is: 1
13// The value of x is: 2
14// The value of x is: 3
15// The value of x is: 4
您可以使用 break 語句在滿足條件時強制退出循環。
範例 3:do-while 循環
do-while 循環是一種結構,循環處理將至少執行一次。由於條件是在處理過程之後評估的,因此即使條件為 false,處理過程也至少執行一次。
1let j: number = 5;
2
3do {
4 console.log("The value of j is: " + j);
5 j++;
6} while (j < 5);
7// Outputs: The value of j is: 5
在此範例中,j 起始值為 5,而 j < 5 的條件為 false,但在 do-while 循環中,不論條件如何,處理過程至少執行一次。
總結
- 只要條件為
true,while循環會重複執行處理過程。 - 如果循環終止條件不明確,則需要留意無限循環的風險。
do-while循環與普通的while循環不同之處在於處理過程至少執行一次。
在 TypeScript 中,while 語句適用於迭代次數不確定或需要動態條件檢查的循環處理。
break 與 continue
您可以在迴圈中使用 break 和 continue。
break用於提前終止迴圈。continue用於跳過當前迭代並進入下一次迭代。
break 的範例
1for (let i = 0; i < 10; i++) {
2 if (i === 5) {
3 break; // Exits the loop when i is 5
4 }
5 console.log(i);
6}
7// Outputs 0, 1, 2, 3, 4
8
9let i = 0;
10while (i < 10) {
11 if (i === 5) {
12 break; // Ends the loop when i is 5
13 }
14 console.log(i);
15 i++;
16}
17// Outputs 0, 1, 2, 3, 4
在此情況下,當 i 等於 5 時執行 break。結果顯示 0 至 4 的數字。
continue 的範例
1for (let i = 0; i < 5; i++) {
2 if (i === 2) {
3 continue; // Skips when i is 2
4 }
5 console.log(i);
6}
7// Outputs 0, 1, 3, 4
8
9let i = 0;
10while (i < 5) {
11 if (i === 2) {
12 i++;
13 continue; // Skips when i is 2
14 }
15 console.log(i);
16 i++;
17}
18// Outputs 0, 1, 3, 4
在此情況下,當 i 等於 2 時執行 continue。結果顯示除了 2 以外的數字。
TypeScript 中的巢狀迴圈
巢狀迴圈是一種在一個迴圈內嵌套另一個迴圈的結構。在 TypeScript 中支援 for、while 與 do-while 等迴圈結構。使用巢狀迴圈可以處理二維陣列(矩陣)並優化基於多種條件的處理。
基本語法
巢狀迴圈的基本語法如下。
1for (let i: number = 0; i < n; i++) {
2 for (let j: number = 0; j < m; j++) {
3 // Processing for the inner loop
4 }
5}每次執行外層迴圈時,內層迴圈都會完成所有的迭代。此結構在處理多重迴圈或資料結構時非常有用。
TypeScript 中巢狀迴圈的範例
遍歷二維陣列
當處理多維資料結構如二維陣列時,經常使用巢狀迴圈。在以下範例中,遍歷了二維陣列的元素,並在控制台打印其值。
1const matrix: number[][] = [
2 [1, 2, 3],
3 [4, 5, 6],
4 [7, 8, 9]
5];
6
7for (let row: number = 0; row < matrix.length; row++) {
8 for (let col: number = 0; col < matrix[row].length; col++) {
9 console.log(`matrix[${row}][${col}] = ${matrix[row][col]}`);
10 }
11}
12// Output
13// matrix[0][0] = 1
14// matrix[0][1] = 2
15// matrix[0][2] = 3
16// matrix[1][0] = 4
17// matrix[1][1] = 5
18// matrix[1][2] = 6
19// matrix[2][0] = 7
20// matrix[2][1] = 8
21// matrix[2][2] = 9
在此範例中,我們正在遍歷二維陣列 matrix。外層循環處理行,內層循環處理列,按順序顯示每個元素。
兩個數組的組合
接下來,我們介紹一個計算兩個數組所有組合的例子。例如,您可以從兩個數組中各取一個元素,輸出所有可能的配對。
1const array1: string[] = ['A', 'B', 'C'];
2const array2: number[] = [1, 2, 3];
3
4for (let i: number = 0; i < array1.length; i++) {
5 for (let j: number = 0; j < array2.length; j++) {
6 console.log(`Pair: (${array1[i]}, ${array2[j]})`);
7 }
8}
9// Output
10// Pair: (A, 1)
11// Pair: (A, 2)
12// Pair: (A, 3)
13// Pair: (B, 1)
14// Pair: (B, 2)
15// Pair: (B, 3)
16// Pair: (C, 1)
17// Pair: (C, 2)
18// Pair: (C, 3)
在這個例子中,創建了字符串數組 array1 和數字數組 array2 之間的所有配對。外層循環從 array1 中提取元素,而內層循環從 array2 中提取元素,顯示每一對配對。
使用三層循環生成座標
例如,使用三層嵌套循環可以生成三維空間中的座標。
1for (let x: number = 0; x < 3; x++) {
2 for (let y: number = 0; y < 3; y++) {
3 for (let z: number = 0; z < 3; z++) {
4 console.log(`Coordinate: (${x}, ${y}, ${z})`);
5 }
6 }
7}
8// Output
9// Coordinate: (0, 0, 0)
10// Coordinate: (0, 0, 1)
11// Coordinate: (0, 0, 2)
12// ...
13// Coordinate: (2, 2, 1)
14// Coordinate: (2, 2, 2)
通過這種方式,使用三層嵌套循環可以輕鬆生成三維空間中的座標。
嵌套循環的性能
嵌套循環很方便,但隨著循環深度的增加,計算成本迅速增加。例如,如果外層循環執行 n 次,內層循環執行 m 次,則總的迭代次數將是 n * m。當進一步嵌套時,計算複雜度將以指數形式增加,可能會影響程序性能。
以下是遍歷三個數組時的計算複雜度。
1const array1: number[] = [1, 2, 3];
2const array2: number[] = [4, 5, 6];
3const array3: number[] = [7, 8, 9];
4
5for (let i: number = 0; i < array1.length; i++) {
6 for (let j: number = 0; j < array2.length; j++) {
7 for (let k: number = 0; k < array3.length; k++) {
8 console.log(`Combination: (${array1[i]}, ${array2[j]}, ${array3[k]})`);
9 }
10 }
11}在此情況下,迴圈執行的次數等於 array1、array2 和 array3 長度的積,總計需要執行 27 次迭代來處理所有組合。
嵌套循環的優化
使用嵌套循環時,可以通過考慮以下優化措施來提高性能。
- 引入提前返回:在達到目標時提前退出循環,以避免不必要的迭代。
- 緩存循環變量:預先緩存循環中使用的變量值(特別是長度和範圍),減少每次計算的成本。
- 更改數據結構:修改數組或對象的結構可以有效加快特定重複過程的速度。
結論
嵌套循環是複雜數據處理和算法中的強大工具。然而,隨著循環深度和迭代次數的增加,可能會出現性能問題。通過適當的優化和仔細的設計,您可以在 TypeScript 中有效利用嵌套循環。
您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。