giza: Giza White Mage (Default)
[personal profile] giza
So, I found myself iterating through form elements today. This code worked just fine on FireFox:
for (key in form.elements) {
   var element = form.elements[key];
   ...
}


So, you'd think that would work in MSIE too, right? Noooo... trying to iterate through the elements that way in MSIE would cause it to pick up methods, language settings, and all sorts of other things not normally found in the elements array. Instead, I had to do this:
for (var i=0; i < form.elements.length; i++) {
   var element = form.elements[i];
   ...
}


And strangely enough, form.elements.length returns only the number of elements in the form, and not methods or whatever else the coming up before.

Oh well, at least I got done the task I was supposed to complete at work today. That's the important part.

(no subject)

Date: 2006-07-21 06:24 pm (UTC)
From: [identity profile] irbisgreif.livejournal.com
This is one reason that Javascript and PHP hurt my brain...

(no subject)

Date: 2006-07-21 06:26 pm (UTC)
From: [identity profile] giza.livejournal.com

PHP is just fine. It's executed on the server side and therefore doesn't break in different browsers.

(no subject)

Date: 2006-07-23 09:56 pm (UTC)
From: [identity profile] taral.livejournal.com
Technically the second one is the right way to do it. The reason the first one works is because Firefox lets it go as a nice shortcut. But the standard says that "for (k in array) { ... }" should also pick up "length" at minimum.

(no subject)

Date: 2006-07-23 10:20 pm (UTC)
From: [identity profile] giza.livejournal.com

Then I say the standard is a little screwed up.

I come from a world (PHP) where for and foreach is just two different ways of iterating through the same data set. I pretty much considered those two operations to be similar, and to produce the same output on a scalar array.

I guess this is one more reason why I hate Javascript.

(no subject)

Date: 2006-07-24 07:35 am (UTC)
From: [identity profile] taral.livejournal.com
Ah, yes. From that perspective it might be confusing.

In Javascript, the foreach construct iterates over all members and fields of the object. This is the only way to find out what all is in an object.

(no subject)

Date: 2006-08-28 08:39 pm (UTC)
From: [identity profile] locoluis.livejournal.com
I found out that for doesn't work unless the index variable was declared (as local to the function?)

What didn't work:

for(i in myobject) {
...
}

What did work:

var i;
for(i in myobject) {
...
}

or (only inside the scope of the for loop)

for(var i in myobject) {
...
}

Profile

giza: Giza White Mage (Default)
Douglas Muth

April 2012

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags