Vòng lặp for...in trong JavaScript
Vòng lặp for...in được sử dụng để lặp qua các thuộc tính của một đối tượng. Khi chúng ta vẫn chưa bàn luận về đối tượng, bạn có thể không cảm thấy thoải mái với vòng lặp này. Nhưng một khi bạn hiểu cách các đối tượng vận hành trong JavaScript, bạn sẽ thấy vòng lặp này rất hữu ích.
Cú pháp
for (variablename in object){ statement or block to execute }
Trong mỗi lần lặp, một thuộc tính từ object – đối tượng được gán tới variablename - tên biến và vòng lặp này tiếp tục tới khi hết tất cả thuộc tính của đối tượng.
Ví dụ
Bạn thử ví dụ sau về vòng lặp for…in. Nó in đối tượng Navigator của trình duyệt web.
<html> <body> <script type="text/javascript"> <!-- 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> <p>Set the variable to different object and then try...</p> </body> </html>
Kết quả:
Navigator Object Properties
serviceWorker
webkitPersistentStorage
webkitTemporaryStorage
geolocation
doNotTrack
onLine
languages
language
userAgent
product
platform
appVersion
appName
appCodeName
hardwareConcurrency
maxTouchPoints
vendorSub
vendor
productSub
cookieEnabled
mimeTypes
plugins
javaEnabled
getStorageUpdates
getGamepads
webkitGetUserMedia
vibrate
getBattery
sendBeacon
registerProtocolHandler
unregisterProtocolHandler
Exiting from the loop!
Set the variable to different object and then try...
Theo Tutorialspoint
Bài trước: Vòng lặp for trong JavaScript
Bài tiếp: Điều khiển vòng lặp trong JavaScript
2.205
Bạn nên đọc
0 Bình luận
Sắp xếp theo
Xóa Đăng nhập để Gửi
Cũ vẫn chất
-
Code Đại Hiệp Chạy Đi mới nhất và cách nhập code
Hôm qua -
Cách thêm máy in vào Windows 10
Hôm qua 2 -
Thủ thuật tạo shortcut chạy ứng dụng dưới quyền Admin
Hôm qua -
Slogan là gì? 90+ Slogan hay, những câu slogan chất, ngắn gọn, ý nghĩa nhất
Hôm qua -
Cách sửa lỗi “Ethernet doesn’t have a valid IP configuration”
Hôm qua -
Bro là gì? Ý nghĩa của Bro?
Hôm qua -
Hướng dẫn sử dụng ổ USB Flash với thiết bị Android
Hôm qua -
Cách tắt app chạy ngầm Windows 11, giảm ngốn RAM trên Win 11
Hôm qua -
Cách lấy dữ liệu từ web vào Excel
Hôm qua -
Hàm RIGHT, cách dùng hàm cắt chuỗi ký tự bên phải trong Excel
Hôm qua