這裡是JavaScript支持的另外一個循環。它被稱為for...in循環。這個循環是用於循環一個對象的屬性。
因為我們還沒有討論的對象,所以使用這一循環可能會感覺不太明白。但是,一旦你會對JavaScript對象了解後,那麼會發現這個循環非常有用。
語法
for (variablename in object){
statement or block to execute
}
從對象每次迭代一個屬性分配給變量名(variablename),這個循環持續到該對象的所有屬性都用盡。
例子:
下面是打印出Web浏覽器的導航器-Navigator 對象的屬性,如下面的例子:
<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>
這將產生以下結果:
Navigator Object Properties appCodeName appName appMinorVersion cpuClass platform plugins opsProfile userProfile systemLanguage userLanguage appVersion userAgent onLine cookieEnabled mimeTypes Exiting from the loop!