for in and arrays

J

Jeff Thies

I think I am misundertanding how "in" works.

I thought I could do this:

var div_array=document.getElementsByTagName('div');

for(var el in div_array){
// I thought el would be an element of that array
// doing this: alert(el) yields either the elements ID or "length"
// why is that?
}

This works, which I thought was the same.

for(var i=0; i< div_array.length; i++){
var el=div_array;
alert(el.innerHTML);
}

Cheers,
Jeff
 
J

Jeff Thies

Well, I see what I did wrong. I shouldn't write javascript after being
up late!

Jeff
I think I am misundertanding how "in" works.

I thought I could do this:

var div_array=document.getElementsByTagName('div');

for(var el in div_array){
// I thought el would be an element of that array

// should be: div_array[el]

// which yields either the ID or it's position or the string "length"
which still puzzles me!

// doing this: alert(el) yields either the elements ID or "length"
// why is that?
}

This works, which I thought was the same.

for(var i=0; i< div_array.length; i++){
var el=div_array;
alert(el.innerHTML);
}

Cheers,
Jeff
 
L

Lasse Reichstein Nielsen

Jeff Thies said:
I thought I could do this:

var div_array=document.getElementsByTagName('div');

for(var el in div_array){
// I thought el would be an element of that array

You caught this one. I do it all the time too. A bad habit from Perl :).
// doing this: alert(el) yields either the elements ID or "length"
// why is that?

What
for (id in obj) { ... }
does is to let id iterate through the enumerable properties of the
object obj.

If obj is an array, the enumerable properties are usually only the
ones with integer names (length, push, etc. are set to be
non-enumerable), but you can add other properties that will be
enumerable.

That is
var arr = [10,20,30];
for (var i in arr) { ... } // i is in the set {0,1,2}

But if you add another property, it is also enumerable.

var arr = [10,20,30];
arr["golfball"] = 40;
for (var i in arr) { ... } // i is in the set {0,1,2,golfball}

What bites you here is that the result of
document.getElementsByTagName is a collection, not an array.
Many of its properties are enumerable.

This works, which I thought was the same.

for(var i=0; i< div_array.length; i++){

It is only the same, if the enumerable properties of div_array are
exactly the interes from zero to length-1.

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,085
Messages
2,570,597
Members
47,218
Latest member
GracieDebo

Latest Threads

Top