ใน TypeScript คำสั่งควบคุมการทำงาน (Control Flow Statements) ใช้เพื่อกำหนดทิศทางและลำดับการประมวลผลของโค้ด ตามเงื่อนไขหรือการวนซ้ำที่ต้องการ คำสั่งเหล่านี้เป็นพื้นฐานร่วมกันของภาษาในตระกูล C-style (รวมถึง JavaScript และ TypeScript)
คำสั่งควบคุมการทำงานหลักที่เราจะกล่าวถึงได้แก่:
-
Conditional Statements:
if/else,switch/case -
Looping Statements:
for,while,do-while,for...of,for...in -
Control Keywords:
break,continue
1. การตรวจสอบเงื่อนไข (Conditional Statements)
A. การใช้งาน if และ else
ใช้สำหรับตรวจสอบเงื่อนไขที่เป็นจริง (true) หรือเป็นเท็จ (false)
ข้อแตกต่างจาก Dart: ใน TypeScript (และ JavaScript) เงื่อนไขในคำสั่ง
ifไม่จำเป็นต้องเป็นค่า Boolean เสมอไป แต่สามารถเป็นค่าใด ๆ ก็ได้ ซึ่งจะถูกแปลงเป็น Truthy (เป็นจริง) หรือ Falsy (เป็นเท็จ) โดยอัตโนมัติ
ค่า Falsy ใน TypeScript/JavaScript ได้แก่:
-
false -
0(ตัวเลขศูนย์) -
""หรือ''(สตริงว่าง) -
null -
undefined -
NaN(Not a Number)
ตัวอย่างการใช้งาน if / else if / else:
let score: number = 75;
if (score >= 80 && score <= 100) {
console.log("Grade A");
} else if (score >= 70) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
// เงื่อนไขอื่นๆ หรือค่าที่ไม่ได้อยู่ในช่วงที่กำหนด
console.log("Grade F");
}
let name: string = 'Ebiwayo';
if (name) { // ตรวจสอบว่า name เป็นค่า Truthy (ไม่เป็นสตริงว่าง)
console.log(`Hello! ${name}.`);
} else {
console.log("Please fill your name.");
}
B. Ternary Operator (Condition Expression)
ใช้สำหรับกำหนดเงื่อนไข if/else แบบสั้น ๆ ในบรรทัดเดียว มักใช้ในการกำหนดค่าตัวแปร
รูปแบบ: condition ? expression_if_true : expression_if_false
let graduated: boolean = true; let msg: string = graduated ? "Congratulation!" : "Study harder"; console.log(msg); // Congratulation!
C. Nullish Coalescing Operator (??)
ใช้สำหรับตรวจสอบว่าค่าตัวแปรเป็น null หรือ undefined หรือไม่ ถ้าใช่ให้ใช้ค่าสำรองที่กำหนดไว้
รูปแบบ: expr1 ?? expr2
Note: Operator นี้เหมือนกับ
??ในภาษา Dart และมีประโยชน์อย่างมากในการจัดการค่าว่างใน TypeScript
let username: string | null = null; // หาก username เป็น null หรือ undefined ให้ใช้ "Guest" let greetingMsg: string = username ?? "Guest"; console.log(greetingMsg); // Guest
2. คำสั่งวนซ้ำ (Looping Statements)
A. Standard for Loop
ใช้สำหรับการวนซ้ำตามจำนวนครั้งที่กำหนด มักใช้ในการเข้าถึงสมาชิกของ Array ด้วย Index
รูปแบบ: for (ค่าเริ่มต้น; เงื่อนไข; การเพิ่ม/ลดค่า)
for (let step = 0; step < 3; step++) {
console.log("Hello, World!");
}
let dayName: string[] = ['Sunday', 'Monday', 'Tuesday'];
for (let i = 0; i < dayName.length; i++) {
console.log(dayName[i]); // Sunday, Monday, Tuesday
}
B. for...of Loop (การวนซ้ำค่า)
ใช้สำหรับวนซ้ำเพื่อดึง ค่า (Value) ของสมาชิกแต่ละตัวจากโครงสร้างข้อมูลที่สามารถวนซ้ำได้ (Iterable) เช่น Array หรือ String
let hobby: string[] = ['Reading', 'Jogging', 'Shopping'];
for (const item of hobby) {
console.log(item);
}
// Output: Reading, Jogging, Shopping
C. for...in Loop (การวนซ้ำ Key/Index)
ใช้สำหรับวนซ้ำเพื่อดึง คีย์ (Key) หรือ Index ของสมาชิกจาก Object หรือ Array (ไม่แนะนำให้ใช้กับ Array)
let person = { name: 'Ebiwayo', age: 24, city: 'Bangkok' };
for (const key in person) {
// Key คือชื่อ Property
console.log(`${key}: ${person[key]}`);
}
// Output: name: Ebiwayo, age: 24, city: Bangkok
D. while และ do-while Loops
ใช้สำหรับการวนซ้ำในกรณีที่ไม่ทราบจำนวนรอบที่แน่นอน และจะหยุดเมื่อเงื่อนไขเป็นเท็จ
-
while: ตรวจสอบเงื่อนไขก่อนการทำงาน -
do-while: ทำงานอย่างน้อยหนึ่งครั้ง ก่อนตรวจสอบเงื่อนไข
let count = 0;
// while loop
while (count < 3) {
console.log(`While Count: ${count}`);
count++;
}
// do-while loop (ทำงานอย่างน้อย 1 ครั้ง)
let i = 0;
do {
console.log(`Do-While Count: ${i}`);
i++;
} while (i < 0); // จะแสดงผล 0 แม้เงื่อนไขเป็นเท็จ
E. break และ continue
-
break: ใช้สำหรับ หยุด การทำงานของ Loop หรือswitchทันที และออกจากบล็อกคำสั่งนั้น -
continue: ใช้สำหรับ ข้าม การทำงานรอบปัจจุบันของ Loop และเริ่มการทำงานในรอบถัดไปทันที
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // ข้ามการทำงานเมื่อ i = 2
}
if (i === 4) {
break; // หยุด Loop เมื่อ i = 4
}
console.log(i); // 0, 1, 3
}
Labels (ป้ายกำกับ): TypeScript รองรับการใช้ป้ายกำกับ (Labels) เพื่อใช้
breakหรือcontinueควบคุมการทำงานของ Loop นอกสุดในการวนซ้ำซ้อนกัน (Nested Loops) เช่นเดียวกับ Dart แต่ในทางปฏิบัติมักไม่นิยมใช้เนื่องจากทำให้โค้ดอ่านยาก
3. การเลือกหลายทางด้วย switch Statement
คำสั่ง switch ใช้สำหรับการเปรียบเทียบค่าเดียวกับหลาย ๆ กรณี (case) ที่เป็นไปได้
ข้อแตกต่างสำคัญจาก Dart (Fall-through): ใน TypeScript/JavaScript เมื่อโค้ดเข้าเงื่อนไข
caseใดแล้ว จะทำงานต่อไปยังcaseถัดไปเรื่อย ๆ (Fall-through) หากไม่มีคำสั่งbreakกำกับไว้ ซึ่งแตกต่างจาก Dart ที่ต้องการการควบคุมอย่างชัดเจนเพื่อป้องกัน Fall-through
ตัวอย่างการใช้งาน switch/case:
let command: string = 'OPEN';
switch (command) {
case 'CLOSED':
console.log("Closed");
break;
case 'PENDING':
case 'APPROVED': // หากไม่มี break จะทำงานต่อจาก PENDING มา APPROVED
console.log("Pending or Approved");
break;
case 'OPEN':
console.log("Open");
// *** จำเป็นต้องมี break; เพื่อหยุดการทำงานของ switch ***
break;
default:
console.log("Something else");
// break; (ที่ default ไม่จำเป็นต้องมี แต่ใส่ไว้ได้)
}
// Output: Pending or Approved (ถ้า command = 'PENDING')
// Output: Open (ถ้า command = 'OPEN')