Is there an easy way to create dynamic variables with Javascript?

julio picture julio · Mar 10, 2010 · Viewed 38.4k times · Source

I've built a data-driven google map with different icons that get assigned to the map depending on the type of item located. So if I have 5 types of landmark, and each gets a different icon (store, library, hospital, etc.)-- what I'd like to do is generate the google icon objects dynamically. I was thinking something like this:

types = array('hospital','church','library','store',etc);
var i=0;
while (i<=types.length) {

    var landmark + i = new google.maps.Icon();
    landmark.image = "icon" + i + ".png";
    i++;
    } 

however, as you've probably guessed, this doesn't work. I also tried using eval, like this:

while (i<=types.length) {
        doIcon(i);
        i++;
    }   

    function doIcon(i){ 
        eval("var landmark" + i + " = new.google.maps.Icon();");
        return eval("landmark" + i);
    }

but it didn't work either-- I'd appreciate any pointers on generating javascript variables dynamically. It's got to be pure js, I could do it in PHP but that's not an option here.

Thanks!

Answer

Plynx picture Plynx · Mar 10, 2010

It's really easy to do: object["variablename"] = whatever;

So for example you could have an object: var Landmarks = {} and you could add to it like so: Landmarks["landmark" + i] = new google.maps.Icon(); and pass it that way.

If you need these variables to be global (why would you?) you can access the global object directly using window.