Forum Moderators: open
[w3schools.com...]
<html>
<body>
<script type="text/javascript">
var x; //No value given?
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars) //What is this line doing?
{
document.write(mycars[x] + "<br />"); //Why does this loop?
}
</script>
</body>
</html>
Thanks in advance for any help!
The For...In works much like a for loop except instead of specifying start and end values and the index incrementing by one, the index goes thru all allocated values in array, if for example you sold the volvo
mycars[0] = "Saab";
mycars[2] = "BMW";
it will still write the remaining two ( x=0 and x=2 )
It works like this: the for statement recognizes the first argument as a property name, and the second as the object. In JavaScript, since functions and arrays are also objects, you can step through all three and retrieve property values and names, although it's most useful for straight objects.
Take this code for example:
// generic object literal
var objectLiteral= { "foo" : 12345, "bar" : 67890 };
// for..in construct
for ( var property in objectLiteral ) {
// step through the object and retrieve property : value pairs
// check to make sure the object actually has a property with this name
if ( objectLiteral.hasOwnProperty("foo") ) {
alert( property +" : " + objectLiteral[property] );
}
}
Note the subscript syntax, i.e. objectLiteral[property]. This could technically be written like objectLiteral.foo for example, but in this case we're iterating through the object as if it were a simple array.
Yes, you could simply do
// typical for loop
// iterator vars
var i, len= objectLiteral.length;
for ( i=0; i< len; i++ ) {
alert( objectLiteral[i] );
}
See, in this case all you get is data back, you can't check an object's properties or get the property name.
Check this JavaScript object reference [developer.mozilla.org] for more details on JavaScript object methods.