简体   繁体   English

如何在JavaScript中将字符串值包装在变量中

[英]How to wrap a string value in variable in JavaScript

In my function below I draw the markers with a chosen icon 在下面的函数中,我用选定的图标绘制标记

function addMarkers(name) {
   var iconVal = "";
   if(name == 'default'){
    iconVal = defaultIcon;
   }
   else if(name == 'school'){
        iconVal = 'schoolIcon';
   }

   marker = new L.Marker(new L.LatLng(a[0], a[1]), { icon: iconVal });
}

My question is how can I pass the variable iconVal as above. 我的问题是如何如上所述传递变量iconVal。 Is there any function that does that like Html.Raw? 有没有像Html.Raw这样的函数?

Don't use variable names for these things. 不要为这些东西使用变量名。 Use an object with properties that are accessible by name: 使用具有可通过名称访问的属性的对象:

var icons = {
    default: new L.Icon.Default(),
    school: L.icon({
        iconUrl: '@Url.Content("~/Content/custom/schoolpin.png")',
        iconSize: [32, 50],
        iconAnchor: [16, 50], 
        popupAnchor: [-3, -76] 
    }),
    test: L.icon({
        iconUrl: '@Url.Content("~/Content/custom/testpin.png")',
        iconSize: [32, 50],
        iconAnchor: [16, 50], 
        popupAnchor: [-3, -76] 
    })
};

function addMarkers(name) {
   var iconVal = icons[name];
   var marker = new L.Marker(new L.LatLng(a[0], a[1]), { icon: iconVal });
}

If the icon's were global variables (and I'm NOT suggesting they should be; just hear me out), you could access the variable like this: 如果图标是全局变量(我不建议它们应该是全局变量;请听我说),您可以像这样访问变量:

   marker = new L.Marker(new L.LatLng(a[0], a[1]), window[icon].iconVal);

It's not quite so straightforward to dynamically access local variables, so use iconVal to hold the whole icon object, instead of a "pointer". 动态访问局部变量并不是那么简单,因此可以使用iconVal来保存整个图标对象,而不是“指针”。 This is assuming that addMarkers directly has access to the local icon objects. 假设addMarkers直接有权访问本地图标对象。

function addMarkers(name) {
  var icon;
  if(name == 'default'){
    icon = defaultIcon;
  }
  else if(name == 'school'){
    icon = schoolIcon;
  }

  marker = new L.Marker(new L.LatLng(a[0], a[1]), icon.iconVal);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM