Vòng lặp for ... in được sử dụng để lặp qua các thuộc tính của đối tượng. Vì chúng ta chưa thảo luận về Đối tượng nên 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 hoạt động trong JavaScript, bạn sẽ thấy vòng lặp này rất hữu ích.
Cú pháp
Cú pháp của vòng lặp ‘for..in’ là:
for (variablename in object) {
statement or block to execute
}
Trong mỗi lần lặp, một thuộc tính từ đối tượng được gán cho tên biến và vòng lặp này tiếp tục cho đến khi hết các thuộc tính của đối tượng.
Thí dụ
Hãy thử ví dụ sau để triển khai 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>
Output
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...