Does the Javascript 'for-in' function, return just an index?
Yes, it will be the index within the collections.
See here:
var mycars = ["Saab", "Volvo", "BMW"];
for (var car in mycars)
{
document.write(mycars[car] + "<br />");
}
As you can see, the use of the variable as an index into the collection.
You can use for each ... in
syntax (introduced in Javascript 1.6) that will iterate over values. See here.
for each...in
- similar tofor...in
, but iterates over the values of object's properties, rather than the property names themselves. (New in JavaScript 1.6.)
As far as I know, Javascript 1.6+ is only used in Firefox at this time.
Yes, the value of the iterator is the name of the property. It's highly frowned upon to use it to loop over arrays, however. For example, consider this:
x = ['a', 'b', 'c'];
x.foo = 'bar';
for (i in x) alert(i); // 0, 1, 2, foo
It's intended for iterating over the members of an object:
x = { a : 'apple', b : 'banana', c : 'carrot' };
for (i in x) {
// and it's best to check that the property actually exists
// on this object, not just on one of its prototypal ancestors:
if (x.hasOwnProperty(i)) {
alert(i); // 'a', 'b', 'c'
}
}
More information about why on the YUI Blog