Home Tutorial Javascript Javascript Bài 8: Vòng lập for…in

Javascript Bài 8: Vòng lập for…in

3 min read
0
129

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, 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 tất cả các thuộc tính của đối tượng cạn kiệt.

Ví dụ

Hãy thử ví dụ sau để triển khai vòng lặp ‘for-in’. Nó in đối tượng Điều hướng 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>

đầu ra

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...
Load More Related Articles
Load More By quangvu
Load More In Javascript

Check Also

Tự làm web chatGPT đơn giản cho phép dùng nhiều OpenAI key

Trong thời đại công nghệ phát triển như hiện nay, chatbot đang dần trở thành một giải pháp…