I am working an a basic learning script below. My main question is in the for() declaration what is the ‘IN’ reserved word and how does the starName relate to it because it is not defined anywhere earlier on the page.
I am trying to understand how the for() loop is “thinking” with that starName in star statement.
<script type="text/javascript">
var star = {};
star["Polaris"] = new Object;
star["Mizar"] = new Object;
star["Aldebaran"] = new Object;
star["Rigel"] = new Object;
star["Polaris"].constellation = "Ursa Minor";
star["Mizar"].constellation = "Ursa Major";
star["Aldebaran"].constellation = "Taurus";
star["Rigel"].constellation = "Orion";
</script>
</head>
<body id="mainbody">
<script type="text/javascript">
for (starName in star) {
var para = document.createElement('p');
para.id = starName;
para.appendChild(document.createTextNode(starName +
": " + star[starName].constellation));
document.getElementsByTagName("body")[0].appendChild(para);
}
</script>
<!-- output below -->
<p id="Polaris">Polaris: Ursa Minor</p>
<p id="Mizar">Mizar: Ursa Major</p>
<p id="Aldebaran">Aldebaran: Taurus</p>
<p id="Rigel">Rigel: Orion</p>
The
for ... insyntax enumerates all enumerable properties of an object.starNamewill be a string that represents the name of the property. You can that access that property (and do plenty of other things) like that:Now there are a couple things you should be aware of when using the
for ... insyntax:Make use of
hasOwnPropertyto safeguard against properties added higher in the prototype chain.Filter out functions. Chances are you are not interested in function but in properties.