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

คำสั่ง for...in loop ใน JavaScript คืออะไร?


คำสั่ง for...in ใช้เพื่อ วนลูปผ่าน Property Names (Keys) ของ Object รวมถึง Prototype Properties (ถ้าไม่ได้กรอง) ใช้สำหรับ Object ไม่ใช่ Array (Array ควรใช้ for...of)

ไวยากรณ์

for (variable in object) {
  // variable = property name (String)
  // object[variable] = property value
}

ตัวอย่างโค้ด

<html>
<body>
  <script>
    var aProperty;
    document.write("Navigator Object Properties<br />");
    for (aProperty in navigator) {
      document.write(aProperty + "<br />");
    }
    document.write("Exiting from the loop!");
  </script>
</body>
</html>

การทำงานกับ Object

const user = {
  name: "John",
  age: 30,
  city: "Bangkok"
};

for (const key in user) {
  console.log(key + ": " + user[key]);
}
// name: John
// age: 30
// city: Bangkok

⚠️ ข้อควรระวังสำคัญ: Prototype Properties

for...in จะวน inherited properties ด้วย ต้องกรองด้วย hasOwnProperty:

// Object.create สร้าง object ที่มี prototype
const proto = { company: "Google" };
const employee = Object.create(proto);
employee.name = "Alice";
employee.role = "Engineer";

for (const key in employee) {
  console.log(key); // name, role, company (รวม prototype!)
}

// ใช้ hasOwnProperty กรอง
for (const key in employee) {
  if (employee.hasOwnProperty(key)) {
    console.log(key); // name, role เท่านั้น
  }
}

// หรือใช้ Object.keys() (แนะนำ ES5+)
Object.keys(employee).forEach(key => console.log(key)); // name, role

❌ ไม่ควรใช้กับ Array

const arr = ["a", "b", "c"];
arr.customProp = "test";

for (const index in arr) {
  console.log(index); // "0", "1", "2", "customProp" (String Keys!)
  console.log(arr[index]);
}

// ปัญหา:
// 1. Index เป็น String ไม่ใช่ Number
// 2. ลำดับไม่รับประกัน (แม้ Browser ใหม่จะเรียงได้)
// 3. รวม Custom Properties เข้ามา
// 4. ช้ากว่า for...of หรือ for แบบปกติ

✅ ตัวเลือกที่ดีกว่าสำหรับ Array

// for...of (ES2015) - แนะนำสุด
for (const value of arr) { console.log(value); }

// forEach - Functional Style
arr.forEach((value, index) => console.log(index, value));

// Standard for - เร็วที่สุด ต้องการ Index
for (let i = 0, len = arr.length; i < len; i++) { ... }

สรุปเมื่อไหร่ใช้ for...in

  • ✅ วน Object Properties (รู้เรื่อง Prototype)
  • ✅ Debug/Inspect Object
  • ❌ วน Array (ใช้ for...of)
  • ❌ ต้องการลำดับ Index แน่นอน