我试图将多个值从数组传递到for语句中,它目前仅在最后一个值上起作用。结果是,它使巴西(而不是巴西和美利坚合众国)为国家着色。如何在不多次运行的情况下将多个值传递给函数?
这是一个小提琴:http://jsfiddle.net/J4643/

这是JS:

var colourCountries = ["United States of America","Brazil"];
var mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/alexplummer.him2149i/{z}/{x}/{y}.png');
var map = L.map('map')
.addLayer(mapboxTiles)
.setView([30, 0], 3);
function style(feature) {
for (var i=1; i<= colourCountries.length; i++) {
 if (colourCountries[i] == feature.properties.name) {
   return {
   weight: 2,
   opacity: 1,
   color: 'white',
   dashArray: '3',
   fillOpacity: 0.3,
   fillColor: '#ff0000'
 };
 }
     else {
   return {
   weight: 1,
   opacity: 1,
   color: '#32B3EF',
   fillOpacity: 1,
   fillColor: '#F3F4E8'
 };
 }
}
}
var geojson, thisCountry;
function onEachFeature(feature, layer) {}
geojson = L.geoJson(countryData, {
    onEachFeature: onEachFeature,
    style: style
}).addTo(map);

最佳答案

有两个错误。数组索引从0而不是1开始。同样,它的编写方式,循环总是在第一圈返回。这有效:

function style(feature) {
  for (var i=0; i < colourCountries.length; i++) {
    if (colourCountries[i] == feature.properties.name) {
      return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.3,
        fillColor: '#ff0000'
      };
    }
  }

  return {
    weight: 1,
    opacity: 1,
    color: '#32B3EF',
    fillOpacity: 1,
    fillColor: '#F3F4E8'
  };
}


Live Demo

或者:

function style(feature) {
  var style1 = {
    weight: 2,
    opacity: 1,
    color: 'white',
    dashArray: '3',
    fillOpacity: 0.3,
    fillColor: '#ff0000'
  };
  var style2 = {
    weight: 1,
    opacity: 1,
    color: '#32B3EF',
    fillOpacity: 1,
    fillColor: '#F3F4E8'
  };

  if ( colourCountries.indexOf(feature.properties.name) !== -1) {
    return style1;
  }
  return style2;
}

10-07 19:02
查看更多