我的代码如下:
Marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][5] === 'Red' ? red_icon : locations[i][5] === 'Purple' ?
purple_icon : blue_icon
});
我为图标设置了条件,如果是红色,则使用红色图标,如果是紫色,则使用紫色图标,否则将使用蓝色。。。。**我的问题是,当我添加另一个条件时,代码不再工作。。。类似:
icon: locations[i][5] === 'Red' ? red_icon : locations[i][5] === 'Purple' ?
purple_icon : locations[i][5] === 'blue' ? blue_icon : green_icon
将案例切换到救援:
let whatIconToUse = green_icon;
switch(locations[i][5]) {
case 'Red':
whatIconToUse = red_icon;
break;
case 'Purple':
whatIconToUse = purple_icon;
break;
case 'blue':
whatIconToUse = blue_icon;
break;
default:
whatIconToUse = green_icon;
break;
}
Marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: whatIconToUse
});
我建议您为此使用关联数组:
var iconMap = {
'Red': red_icon,
'Blue': blue_icon,
// etc
}
然后你的代码变得更容易阅读:
var icon = locations[i][5];
Marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: iconMap[icon]
});
考虑使用切换语句
let icon = '';
switch(locations[i][5]) {
case "Red":
icon = red_icon
break;
case "Purple":
icon = purple_icon
break;
case "blue":
icon = blue_icon
break;
}
Marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: icon
});
或者你可以使用(肮脏的(技巧
Marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: eval(locations[i][5].toLowerCase() + '_icon')
});
您需要使用括号来嵌套三元运算符(形式为boolean ? value_if_true : value_if_false
的运算符
在您的特殊情况下,
icon: locations[i][5] === 'Red' ? red_icon : (locations[i][5] === 'Purple' ?
purple_icon : (locations[i][5] === 'blue' ? blue_icon : green_icon))
然而,switch
语句会使事情变得更可读、更易于扩展:
let color;
switch(locations[i][5]) {
"Red": { color = red_icon; break; }
"Purple": { color = purple_icon; break; }
// add all cases here
}
为什么不简单地说:
icon: locations[i][5].toLowerCase() + "_icon"
"红色"->quot;red_ icon";
"紫色"->quot;purple_icon";