JavaScript สำหรับ ... ในลูป

for...inloop ใช้ในการวนซ้ำคุณสมบัติของวัตถุ เนื่องจากเรายังไม่ได้พูดถึง Objects คุณอาจไม่สบายใจกับการวนซ้ำนี้ แต่เมื่อคุณเข้าใจว่าวัตถุทำงานอย่างไรใน JavaScript คุณจะพบว่าการวนซ้ำนี้มีประโยชน์มาก

ไวยากรณ์

ไวยากรณ์ของ 'for..in' loop คือ -
for (variablename in object) {
   statement or block to execute
}

ในการวนซ้ำแต่ละครั้งคุณสมบัติหนึ่งรายการจาก object ได้รับมอบหมายให้ variablename และวนซ้ำนี้จะดำเนินต่อไปจนกว่าคุณสมบัติทั้งหมดของวัตถุจะหมดลง

ตัวอย่าง

ลองใช้ตัวอย่างต่อไปนี้เพื่อใช้งานลูป 'for-in' มันพิมพ์เว็บเบราว์เซอร์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...