Javascript-forin-loop

提供:Dev Guides
移動先:案内検索

JavaScript _for …​ in_ループ

*for ... in* ループは、オブジェクトのプロパティをループするために使用されます。 オブジェクトについてはまだ説明していませんが、このループに慣れていないかもしれません。 しかし、JavaScriptでオブジェクトがどのように動作するかを理解すると、このループは非常に便利です。

構文

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

各反復で、 object の1つのプロパティが 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...