JavaScript for ... in 循环

for ... in 循环用于循环对象的属性。由于我们还没有讨论过对象,你可能对这个循环感到不舒服。但是一旦你理解了对象在JavaScript中的行为,你会发现这个循环非常有用。

语法


'for..in'循环的语法是:

for (variablename in object) {
   statement or block to execute
}


在每次迭代中,对象中的一个属性被分配给 variablename ,并且此循环继续,直到对象的所有属性都用完为止。

示例

尝试以下示例来实现'for-in'循环。它打印Web浏览器的 Navigator 对象。

在线演示

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


输出

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