Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

for...of Loop ใน JavaScript วนลูป Iterable Objects

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 ใช้ได้

เปรียบเทียบ

LoopIteratesUse For
for...ofValuesArray, String, Map, Set
for...inKeys (String)Object Properties (Enumerable)
forEachValues + IndexArray (ไม่ Break ได้)

ผลลัพธ์

H
e
l
l
o