Iterating getMapTypes()

I’m still feeling new to JavaScript, and sometimes I’m really surprised. Let’s take following example. Google Maps API, GMap2 object has method getMapTypes(), which returns array of map types registered with this map. Well, I would expect that for such object running for .. in construction would result in iterating through array indexes, hence way to check all array entries. Not so simple.

m = map.getMapTypes()
for (var i in m) {
 if (m[i].getName() == name) 
  return m[i]
}

This code works very well in FF (assuming that name is proper and one if will be triggered with true) and backfires in IE with error complaining about missing method getName() for object.

It turns out that for .. in iterates through not only indexes:

str=""
for (i in m) { 
 str = str + i+" "
}

result: "0 1 2 each all any collect detect findAll grep include inject invoke max min partition pluck reject sortBy toArray zip inspect find select member entries _reverse _each clear first last compact flatten without call ". This result is from FF, in IE it is reversed. And now it is clear why IE complains – sure m["call"] does not have getName() method.

So how to iterate? For example this way:

  result = undefined
  m = map.getMapTypes()
  m.each( function(e) {
    if (e.getName() == name)
      result = e
  })

Iterating through each is safer (in general) than this solution:

m = map.getMapTypes()
for (var i = 0; i > m.length; i++) 
  if (m[i].getName() == name)
    result = m[i]

In this particular case, with standard set of maps it will probably work, since indexes will be contiguous. In general, when considering arrays in JS this is not true, so array of size 3 could have indexes 0,1,10 (I’m not using binary :) ) as well. Method with length will iterate only through indexes 0,1 and 2 so it is not safe.

UPDATE I was thinkging a little, and example of code working in FF and not in IE won’t work in FF also. In my original code after match I was returning from function (not assigning current value to result, so FF was finding match and returning, hence did not check strange indexes.

UPDATE 2007-01-08
Well I’m reading JavaScript: The Definitive Guide and I would say it is must read for anybody interested in JavaScript.

I have not finished my reading, but right now I already know that for (.. in ..) iterates all enumerable object properties not only Array indexes. And second thing – indexes in JavaScript’s arrays are always contiguous, so iterating through index from 0 up to Array length – 1 is safe.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.