คำสั่ง for loop เป็น รูปแบบลูปที่กะทัดรัดที่สุด รวม 3 ส่วนสำคัญในบรรทัดเดียว:
- Initialization: กำหนดค่าเริ่มต้นตัวนับ (รันครั้งแรกเท่านั้น)
- Test Condition: ตรวจสอบเงื่อนไขก่อนแต่ละรอบ (true = ทำต่อ, false = หยุด)
- Iteration: อัปเดตตัวนับหลังแต่ละรอบ
ไวยากรณ์
for (initialization; testCondition; iteration) {
// โค้ดที่จะทำซ้ำ
}
ตัวอย่างโค้ด
<html>
<body>
<script>
var count;
document.write("Starting Loop<br />");
for (count = 0; count < 10; count++) {
document.write("Current Count: " + count + "<br/>");
}
document.write("Loop stopped!");
</script>
</body>
</html>
ผลลัพธ์
Starting Loop Current Count: 0 Current Count: 1 ... Current Count: 9 Loop stopped!
รูปแบบต่างๆ ของ for Loop
1. มาตรฐาน (Standard)
for (let i = 0; i < 5; i++) { ... }
2. ไม่มี Initialization (มีตัวแปรอยู่แล้ว)
var i = 0;
for (; i < 5; i++) { ... }
3. ไม่มี Test Condition (Infinite Loop)
for (let i = 0; ; i++) {
if (i > 10) break;
}
4. ไม่มี Iteration (อัปเดตในบล็อก)
for (let i = 0; i < 5; ) {
console.log(i);
i++; // อัปเดตในบล็อก
}
5. หลายตัวแปร (Multiple Variables)
for (let i = 0, j = 10; i < j; i++, j--) {
console.log(i, j); // (0,10), (1,9), (2,8)...
}
6. for...of (ES2015) - วนลูปค่าโดยตรง
for (const item of [10, 20, 30]) {
console.log(item); // 10, 20, 30
}
7. for...in - วนลูป Key/Property
for (const key in {a:1, b:2}) {
console.log(key); // "a", "b"
}
แนวทางปฏิบัติที่ดี
- ใช้
letหรือconstแทนvar(Block Scope ป้องกันบั๊ก) - ใช้
for...ofสำหรับ Array/Iterable (อ่านง่าย ไม่ต้องจัดการ Index) - ใช้
for...inสำหรับ Object Properties เท่านั้น - หลีกเลี่ยงการแก้ไข Array ขณะวนลูป (ใช้
filter,mapแทน) - ย้ายค่าคงที่ออกนอกลูป:
const len = arr.length; for (let i=0; i
ข้อผิดพลาดที่พบบ่อย
- Off-by-one Error:
i <= lengthแทนi < length - Infinite Loop: เงื่อนไขไม่เป็น false เลย
- ใช้
varในลูปทำให้iLeak ออกมานอก Scope