for...of วนลูปค่า (Value) ของ Iterable Objects: Array, String, Map, Set, NodeList, Arguments, Generators
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>for...of Loop</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result, .sample { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>for...of Loop in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to iterate string with for...of </h3>
<script>
let resEle = document.querySelector(".result");
let sampleEle = document.querySelector(".sample");
let str = "Hello";
sampleEle.innerHTML = str;
document.querySelector(".Btn").addEventListener("click", () => {
for (let char of str) {
resEle.innerHTML += char + "<br>";
}
});
</script>
</body>
</html>
คำอธิบาย
for (const item of iterable)-itemคือ Value ไม่ใช่ Index- Array: วนค่า Element
- String: วน Character (รองรับ Unicode/Surrogate Pairs ถูกต้อง)
- Map: วน [key, value] | Set: วน Value
- Object ธรรมดา: ไม่ใช่ Iterable ใช้
for...inหรือObject.entries() - Control:
break,continueใช้ได้
เปรียบเทียบ
| Loop | Iterates | Use For |
|---|---|---|
| for...of | Values | Array, String, Map, Set |
| for...in | Keys (String) | Object Properties (Enumerable) |
| forEach | Values + Index | Array (ไม่ Break ได้) |
ผลลัพธ์
H
e
l
l
o