循环中的JavaScript


for...in循环用于遍历对象的属性。由于我们尚未讨论对象,因此你可能不喜欢此循环。但是一旦了解了对象在JavaScript中的行为,你就会发现此循环非常有用。

语法


for..in循环的语法为:

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

在每次迭代中,object被分配给变量名并且此循环一直进行到对象的所有属性用尽为止。

请尝试以下示例来实现“ for-in”循环。它会打印网络浏览器的navigator object.

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