У меня есть следующий код, и мне нужно получить доступ к переменной «плотность» и поместить его во всплывающее окно. Плотность определяется в функции mapCities, но маркеры, которые я добавляю, и всплывающие окна, которые я создаю, создаются в для l oop вне функции городов карты, что приводит к ReferenceError: плотность не определен как индекс. html: 151: 42. Это ошибка ожидается. Я просто не знаю, как получить доступ к этой переменной плотности. Должно ли это быть с вложенным l oop?
function mapCities(units) {
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i];
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var cityXY = cityCoords[i];
var density = calcPopDensity(cityNumPeeps, cityZone, units); // call calcPopDensity passing population, cityZone and units as arguments
console.log(density);
}
};
function calcPopDensity(cityNumPeeps, cityZone, units) {
if (units == "miles") {
return cityNumPeeps / cityZone // calculate population density in miles and return it
} else if (units == "km") {
return cityNumPeeps / cityZone * 1.60934 // calculate population density in miles and return it
}
};
for (var i = 0; i < cities.length; i++) {
var cityName = cities[i];
var cityNumPeeps = cityPops[i];
var cityZone = cityAreas[i];
var cityXY = cityCoords[i];
var popup = `<b>${cityName}</b><br>
<b>population</b>: ${density}<br>`
L.marker(cityXY).addTo(map) // add marker to map based on cityCoords array and bind to popup
.bindPopup(popup);
console.log(popup)
//if statement determines units to place in popup text
if (units == "miles") {
popup += `miles`; // add text if if var density returns miles
} else if (units == "km")
popup += `kilometers`; // add text if if var density returns kilometers
L.marker(cityXY).addTo(map) // add popup again based on if statement
.bindPopup(popup);
console.log(popup)
}
```