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 vòng lặp For ... in trong JavaScript

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ụ vòng lặp For ... in trong JavaScript

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...

Viết câu trả lời

Drop Images

0 Bình luận