สำหรับ…วนซ้ำ
ลูป “for...in” ใช้เพื่อวนซ้ำคุณสมบัติของอ็อบเจ็กต์
นี่คือไวยากรณ์ −
ไวยากรณ์
for (variablename in object) {
statement or block to execute
} คุณสามารถลองเรียกใช้ตัวอย่างต่อไปนี้เพื่อใช้ลูป 'for-in' มันพิมพ์วัตถุ Navigator ของเว็บเบราว์เซอร์
ตัวอย่าง
สาธิตสด
<html>
<body>
<script>
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator) {
document.write(aProperty);
document.write("<br />");
}
document.write ("Exiting from the loop!");
</script>
</body>
</html> สำหรับ…ของลูป
การวนซ้ำ “for…of” ใช้เพื่อวนซ้ำอ็อบเจกต์ที่วนซ้ำได้ ซึ่งรวมถึง Map, Array, อาร์กิวเมนต์ ฯลฯ
ไวยากรณ์
นี่คือไวยากรณ์ −
for (variablename of iterable){
statement or block to execute
} ตัวอย่าง
นี่คือตัวอย่างที่แสดงการวนซ้ำด้วย for…of loop
สาธิตสด
<!DOCTYPE html>
<html>
<body>
<script>
let itObj= [20, 30, 40, 50];
for (let res of itObj) {
res += 1;
document.write("<br>"+res);
}
</script>
</body>
</html> ผลลัพธ์
21 31 41 51