JavaScript:如何匹配字符串和var?

时间:2014-05-06 10:27:29

标签: javascript string var

我需要你的帮助,

我希望activeLayers = [bus,stops,slot1]而不是activeLayers = ["bus","stops","slot1"]如何管理?换句话说,我想"转换"对象的字符串,应该引用。

遗憾的是,它在这里工作的还有一些代码可能有帮助

window.onload = function () {
                var validLayers = {
                    slot1 : new L.LayerGroup(),
                    places : new L.LayerGroup(),
                    stops : new L.LayerGroup()
                    };
                    var platz = L.MakiMarkers.icon({icon: "embassy", color: "#f00", size: "l"});
                    var extern = L.MakiMarkers.icon({icon: "college", color: "#FF9900", size: "l"});


                        // Wichtige Plätze
                        L.marker([49.99264845,8.24160625696918], {icon: platz}).bindPopup('Wiese vor dem ZDV').addTo(validLayers.places);
                        L.marker([49.99454,8.24384], {icon: platz}).bindPopup('Rote Infobox').addTo(validLayers.places);
                        L.marker([49.99182355,8.23384953468164],{icon:platz}).bindPopup('Zentralmensa').addTo(validLayers.places);
// Get url parameters
var params = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
    params[key] = value;
});


if( params.layers) {
    var activeLayers = (function(arr) {
        var l = arr.length, i, ret = {};
        for( i=0; i<l; i++) ret[i] = validLayers[arr[i]];
        return ret;
    })(params.layers.split(","));
}

// Create map
var map = new L.Map('map', {
    center: [params.lat || 49.99238, params.lng || 8.23779],
    minZoom: 12,
    maxZoom: 18,
    zoom: params.zoom || 15,
    layers: activeLayers || [validLayers.places, validLayers.stops ,validLayers.slot1]
});



                var baseLayers = {
                };

                var overlays = {
                    "Sonstiges": validLayers.places,
                    "Bus": validLayers.stops,
                    "Slot 1": validLayers.slot1,
                    "Slot 2": validLayers.slot2,
                    "Slot 3": validLayers.slot3,
                    "Slot 4": validLayers.slot4
                };



                L.control.layers(baseLayers, overlays).addTo(map);

                L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map);
}

这是我用来显示网站的网址

campusmap.html LAT = 49.99684&安培; LNG = 8.24811和缩放= 18&安培;多层=地方,总线,slot1中

1 个答案:

答案 0 :(得分:3)

如果我正确理解您的问题,您希望能够在查询字符串中引用某些变量吗?如果是这样,请考虑尝试:

var validLayers = {
    slot1: new L.LayerGroup(),
    places: new L.LayerGroup(),
    stops: new L.LayerGroup()
};

// get url parameters
// ...

if( params.layers) {
    var activeLayers = params.layers.split(",").map(function(key) {
        return validLayers[key];
    });
}

此处,validLayers被用作白名单,因此只能引用您允许的内容。