How to “generate” unique variables?

折月煮酒 提交于 2019-12-23 03:18:10

问题


I'm currently working on a Google Map, and now I want to "generate" pins from an API. But then I get stuck, because a pin looks like this:

var imageDriver = 'marker.png';
var DriverLatLng = new google.maps.LatLng(location.lat, location.lng);
var driverMarker = new google.maps.Marker({
    position: DriverLatLng,
    map: map,
    icon: imageDriver,
    title: drivers[0].name
});
}

I want to create a function of some sort that could "generate" these variables with a prefix. Check an example below:

var imageDriver0;
var DriverLatLng0;
var driverMarker0;
position: DriverLatLng0,
map: map,
icon: imageDriver0,
title: drivers[o].name

These variables must be unique of course so they don't "collide". I have this for-loop that counts all "drivers" inside my API. Could I somehow make this for-loop to create these pins? Example:

    driversRealtime();
function driversRealtime() {
    setInterval(function () {
        var url = "http://blackcab.didair.se/api/drivers";
        var lat;
        var lon;
        var name;
        var id;
        $.getJSON(url,

        function (response) {
            for (var i = 0; i < response.drivers.length; i++) //Counts data-elemements inside 
                lat = response.drivers[i].currentLat;
                lon = response.drivers[i].currentLon;
                name = response.drivers[i].name;
                id = response.drivers[i].profileId;
            console.log(lat);
            console.log(lon);
            console.log(name);
            console.log(id);
        });
    }, 3000); //Delay in milliseconds
}

回答1:


It's possible to create variable names dynamically, but almost always pointless.

Use an array instead or a suffix, and put the values as properties in an object in the array. Example:

var points = [];

var point = {
  "url": url,
  "lat": lat,
  "lng": lng,
  "name": name,
  "id": id
};
points.push(point);


来源:https://stackoverflow.com/questions/15894755/how-to-generate-unique-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!