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

后端 未结 5 458
你的背包
你的背包 2020-12-01 07:06

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

5条回答
  •  一整个雨季
    2020-12-01 07:22

    If you're going to do it using a declared object such as Landmark["landmark" + i], you really may as well use an index array rather than an associative, it's much easier for iteration. Objects aren't really used with indexed properties because Arrays do a much better job of it:

    var myObj =           // object version
    {
       "item0": "blah",
       "item1": "blah"
       // etc
    }
    var myArr =           // array version
    [
       "blah",
       "blah"
       // etc
    ]
    

    Much more sensible to use the array:

    landmarks = []; // new array
    types = array('hospital','church','library','store',etc);  
    var i=0;  
    while (i<=types.length) {  
        landmarks.push(new google.maps.Icon());
        landmarks[i].image = "icon" + i + ".png";
        i++;  
    }
    

    It makes more sense to do it that way and for...in loops on objects can get a bit messy with prototyped properties being enumerable, etc.

    If you're trying to make a variable global, add it to the window object:

    var myCustomVar = "landmark" + i;
    window[myCustomVar] = new google.maps.Icon();
    
    alert(landmark0);
    

    But this would be polluting the global namespace with many unnecessary variables. So you'd still be better with an array:

    window.landmarks = [];
    landmarks.push(new google.maps.Icon());
    // etc...
    

提交回复
热议问题