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

后端 未结 5 383
你的背包
你的背包 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...
    
    0 讨论(0)
  • 2020-12-01 07:22

    You'd be better off creating a javascript object which you can use somewhat like an associative array is used in PHP:

    var types = ['hospital','church','library','store'];
    var landmarks= {};
    for (var i in types) {
        landmarks[types[i]]= new google.maps.Icon();
        landmarks[types[i]].image = "icon" + i + ".png";
    } 
    alert(landmarks['hospital'].image);  // displays "icon0.png"
    
    0 讨论(0)
  • 2020-12-01 07:31

    Do you really need those variables? Can't you do with this:

    var types = ['hospital','church','library','store'];    
    for(var i =0; i < types.length; i += 1) (new google.maps.Icon()).image = "icon" + i + ".png";
    

    Modifications done based on comment:

    icon name pattern changed from icon + index + .png to icon + type + .png and saving the results of the loop.

    types = ['hospital','church','library','store'];
    var landmarks = {};
    
    
    // images names are of the form icon + type + .png
    function createIcon(type) 
    { 
        var icon = new google.maps.Icon();
        icon.image = "icon" + type + ".png";
        return icon;
    }
    
    // mapping of landamarks by type and icon
    for (var i = 0, len = types.length; i < len; i++)
    {
        landmarks[types[i]] = createIcon(types[i]);
    }
    

    the result is : { hospital : icon, church : icon, ... }

    where icon is a google map icon that has an image attribute that is a string of the form "icon{type}.png" , e.g, iconhostpital.png, iconchurch.png.

    To use the icons write landmarks.type where type is one the names in the array of types, e.g. landmarks.hospital.

    if the image names are of the form icon + number + .png, and the number for each type is equivalent to its index in the array replace the call createIcon(type[i]) for createIcon(i).

    0 讨论(0)
  • 2020-12-01 07:35

    Just to answer your question directly (although please note that this is not the solution you want. Check out the other answers. This is just for documentation!), here's a copy-paste from a JavaScript console:

    > window["myNamedVar"] = "Hello, World!";
    > console.log(myNamedVar);
      "Hello, World!"
    
    0 讨论(0)
  • 2020-12-01 07:37

    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.

    0 讨论(0)
提交回复
热议问题