views:

184

answers:

1

I am using google maps api v3 and have an array of arrays object:

MVCArray.<MVCArray.<LatLng>>

I want to iterate over this. I see that MVCArray has a method forEach which uses a call back, but I have no idea how to use this (I haven't done much js). The api defines this method as follows:

forEach(callback:function(*, number)))

Could somebody please show me an example of how to use this given an MVCArray of MVCArrays (I need to pull out each LatLng object)?

+2  A: 

In JavaScript, you can pass around functions in the same way you can pass around any other sort of data. There are two usual ways of approaching this.

First, you could define a function in the usual way and give it a name:

function myHappyFunction(item, index) {
   // Do things using the passed item and index
}
...forEach(myHappyFunction);

Here you're passing the function you've created into the forEach function. myHappyFunction will now get called a bunch of times, each time passing a different item from the list.

Alternatively, you can avoid the need to come up with a clever function name by just passing a function DIRECTLY, like so:

...forEach(function(item, index) {
    // Do things using the passed item and index
});

This behaves the same way, but without the need to develop a unique name for each and every function you might want to pass around.

VoteyDisciple