if数组元素在for循环内部有条件



我在谷歌地图上绘制的JavaScript数组中返回了一系列位置。

我正试图根据其中一个数组元素的值来更改标记图标的类型,比如

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));
}

但遇到

Uncaught SyntaxError: Unexpected token (

我错过了什么?

我错过了什么?

您正在将流代码放在对象初始化器的中间:

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));
}

你不能那样做 我不确定你想在那里做什么你发布了一条澄清评论:

在新的google.maps.Marker({我需要能够设置图标:'/ig/a.png'或图标:'/Ig/b.png'取决于位置的值[I][3]

所以我对一个属性的猜测是正确的:你可以使用条件运算符:

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'
});

其中,如果locations[i][3] == "Yes"为真,则icon属性的值将为'/img/a.png',否则为'/img/b.png'

最新更新