Mục đích
Duyệt qua tên thuộc tính (keys) liệt kê được (enumerable) của object, bao gồm cả prototype chain.
Cú pháp
for (const key in object) {
// key là string
// object[key] là giá trị
}
Ví dụ: Duyệt Navigator object
<script>
document.write("Navigator Object Properties<br>");
for (const prop in navigator) {
document.write(prop + "<br>");
}
document.write("Ket thuc!");
</script>
⚠️ Cạm bẫy với Array
var arr = ["a", "b", "c"];
arr.customProp = "extra";
for (const key in arr) {
console.log(key); // "0", "1", "2", "customProp" (thứ tự không đảm bảo)
}
// Key là STRING "0", "1" – không phải number
Best practice cho Array
- Dùng
for...of(duyệt giá trị). - Dùng
for (let i=0; i(cần index). - Dùng
arr.forEach((v,i)=>{}).
Lọc prototype
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
// chỉ own property
}
}
// Hoặc ES2022: Object.hasOwn(obj, key)