Listing the options of a Select gives different results in FF and IE
In my JavaScript code I'm trying to list the options (and their values) of a Select. Here's a snippet of code (I'm using the YUI2 library...the log statement just puts text in a logger):
for (var opt in mySelect.options)
{
YAHOO.log('my opt, val: ' + opt + ', ' + mySelect.options[opt].value);
}
In Firefox I get the following (correct) output:
my opt, val: 0, 2
my opt, val: 1, 1
my opt, val: 2, 3
my opt, val: 3, 4
my opt, val: 4, 0
but 开发者_开发百科in Internet Explorer 7 I get:
my opt, val: language, undefined
my opt, val: scrollHeight, undefined
my opt, val: isTextEdit, undefined
my opt, val: currentStyle, undefined
my opt, val: document, undefined
I'm a bit surprised to say the least. I even tried for (var opt in (mySelect.options)) and I changed the name of the variable opt just in case. Nothing made a difference.
If I code the loop like this:
for (var idx=0; idx< mySelect.options.length; idx++)
{
YAHOO.log('my idx, val: ' + idx + ', ' + mySelect.options[idx].value);
}
then IE works fine as well.
Why did the first way not work? I thought the for/in loop worked the same way as a for loop.
Thanks,
Paul
for
/ in
loops loop over every property in an object.
You aren't seeing these properties in Firefox because they're marked as [DontEnum]
.
You should use ordinary for
loops to loop over arrays.
For ordinary arrays, you can get away with a for
/ in
loop by skipping keys if !obj.hasOwnProperty(key)
, but I'm not sure whether that will work for DOM objects.
精彩评论