Welcome to WebmasterWorld Guest from 23.20.223.88

Forum Moderators: open

Message Too Old, No Replies

Please explain the For.In statement

     
6:36 am on Apr 10, 2009 (gmt 0)

5+ Year Member



I'm new to JavaScript and stumbled upon the For...In statement. I'm not sure why this loops...
Furthermore, I'm not sure what the benefit is of looping this way.

[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!

7:18 am on Apr 10, 2009 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Try rewriting this using a "for loop" instead as an exercise,

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 )

2:22 am on Apr 12, 2009 (gmt 0)

5+ Year Member



for..in is a construct that allows you to loop through an object and retrieve data based on property names, vs. simply referring to an iterator (e.g. the ubiquitous "i" var). It's useful in certain situations where you're dealing with objects, e.g. a JSON message return from an XMLHttpRequest call to a server resource.

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.

 

Featured Threads

Hot Threads This Week

Hot Threads This Month