Javascript三元运算符

Javascript ternary operator

本文关键字:三元 运算符 Javascript      更新时间:2023-09-26

我正在为谷歌地图创建两个不同的图标。然而,只有一个图标出现。一个名为facility的下拉选择将允许一个基于值'8'的图标,所有其他值创建另一个图标。

var marker = createMarker(latlng, name, address, city, state, zipcode, telephone, images, url, facility);

function createMarker(latlng, name, address, city, state, zipcode, telephone, images, url, facility) { 
  var html = "<div id='infodiv'>" + name + "<br/><h4>" + address + "<br/>" + city + ", " + state + " " + zipcode + "<br/>" + (formatPhone(telephone)) + "</h4><div class='infoimage'><img src='" + images + "'></div><div class='footer'><a href='http://" + url + "'>" + url + "</a></div></div>";
  var marker = new google.maps.Marker({
    icon: icon2,
    icon: (facility == 8) ? icon : icon, 
    map: map, 
    position: latlng 
  });

图标如下:

var icon = new google.maps.MarkerImage("./images/plum_flag.png", 
new google.maps.Size(35, 52), new google.maps.Point(0, 0), 
new google.maps.Point(0, 52));
//callup the orange icon
var icon2 = new google.maps.MarkerImage("./images/orange_flag.png", 
new google.maps.Size(26, 39), new google.maps.Point(0, 0), 
new google.maps.Point(0, 39));

唯一显示的图标是'var icon = new google.maps.MarkerImage("./images/plum_flag.png",'无论选择选项是什么....

(facility == 8) ? icon : icon,

表示:如果facility8,则使用icon,否则使用icon。不是很有用,因为总是使用icon

你可以这样写:

(facility == 8) ? icon : icon2,

您可能会感到困惑,因为icon指的是前面设置的icon: icon2。然而,两个icon都指向完全相同的东西,因此您不会看到任何差异。

由于您使用三元操作符定义icon,因此第一个icon:定义也可以省略(第二个icon:定义无论如何都会覆盖它)。

这是错误的:

  icon: icon2,
  icon: (facility == 8) ? icon : icon, 

你给icon赋了两次值,第二次都是一样的