[英]if array element conditional inside for loop
I have a series of locations returning in an array in JavaScript that I'm plotting on a Google Map. 我在Google地图上绘制的JavaScript数组中返回了一系列位置。
I'm trying to change the type of marker icon depending the value on one of the array elements like so 我试图根据这样的数组元素之一的值来更改标记图标的类型
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
if (locations[i][3] == "Yes") {
console.log("yes")
} else {
console.log("no")
}
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
but running into 但是碰到
Uncaught SyntaxError: Unexpected token (
What am I missing? 我想念什么?
What am I missing? 我想念什么?
You're putting flow code in the middle of an object initializer: 您正在将流代码放在对象初始化器的中间:
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
if (locations[i][3] == "Yes") { // ====
console.log("yes") // ====
} else { // ==== Here
console.log("no") // ====
} // ====
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
You can't do that. 你不能那样做。 I'm not sure what you're trying to do there You've posted a clarifying comment: 我不确定您要在该做什么。您已发布了一个澄清的评论:
within the new google.maps.Marker({ I need to be able to set icon: '/img/a.png' or icon: '/img/b.png' depending on the value of locations[i][3] 在新的google.maps.Marker中({我需要能够根据位置的值设置图标:'/img/a.png'或图标:'/img/b.png'[i][3]
So my guess about a property was correct: You can do that with the conditional operator: 因此,我对某个属性的猜测是正确的:您可以使用条件运算符来做到这一点:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3] == "Yes" ? '/img/a.png' : '/img/b.png'
});
...where the icon
property's value will be '/img/a.png'
if locations[i][3] == "Yes"
is true, or '/img/b.png'
if not. ...如果locations[i][3] == "Yes"
为true,则icon
属性的值为'/img/a.png'
,否则为'/img/b.png'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.