views:

59

answers:

1

Sorry, this is probably a duplicate question, but how can I iterate over a list in Javascript inside another object without using eval()?

See pseudocode in CAPITALS below:

polygon = polygon['coordinates']; //list object
var polygon = new CM.Polygon([
   FOR POLY IN POLYGON {
       new CM.LatLng(poly[1], poly[0]),
}
]);

Obviously, I don't want a real for-loop inside the CM.Polygon object (a CloudMade map object), what I want is simply to output each LatLng in the list in turn.

Thanks!

+1  A: 

Why don't you want to use a real for loop? My suggestion would be to use a self-executing function eg:

polygon = polygon['coordinates']; //list object
var polygon = new CM.Polygon(
  (function(){
    var oput = [], x, y;
    for ( x=0,y=polygon.length ; x<y ; x++){
      oput.push(new CM.LatLng(polygon[x][1],polygon[x][0]));
    }
    return oput;
  }())
);
Rixius
I like this! Didn't even know you could do that! *scraps his own solution* ha
Parris
yeah, it's an amazing feature of Functional scope.
Rixius
I'm familliar with `for(;;){}` syntax in JS but not `for(,,,){}`. Is that a typo?
fsb
yes typo. changing now... >.>
Rixius
the first comma is saying x = 0 AND y = length, so it keeps a comma delimeter
Rixius
so clever! thanks!
AP257