gpt4 book ai didi

javascript - 如何在JQuery中使用带有 'for'的多个数组元素

转载 作者:行者123 更新时间:2023-11-28 01:27:16 24 4
gpt4 key购买 nike

我正在尝试将数组中的多个值传递到 for 语句中,它目前仅处理最后一个值。结果是它为巴西国家着色,而不是巴西美利坚合众国。如何将多个值传递到函数中而不需要多次运行它?这是一个 fiddle :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);

最佳答案

有 2 个错误。数组索引从 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;
}

关于javascript - 如何在JQuery中使用带有 'for'的多个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22543019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com