[英]Uncaught (in promise) TypeError: Cannot read property '0' of undefined. Pulling from a csv file to populate an array
I am using the Leafleft Map API and a csv file to place markers on an interactive map (like an embedded google map) and I want to be able to click on a marker so that it changes the contents of a div tag (here with the infoName 的 ID)在網站上。
我從最后一行代碼中得到一個錯誤,說“無法讀取未定義的屬性'0'”,我認為這與承諾和數據獲取有關,也許與 scope 有關。 這是我的代碼:
var restaurants = [];
makeMarkers();
async function getData() {
const response = await fetch('restaurantData.csv');
const data = await response.text();
const rows = data.split(/\n/).slice(1);
rows.pop();
for (var i = 0; i < rows.length; i++) {
const col = rows[i].split(',');
restaurants[i] = col;
}
}
async function makeMarkers() {
await getData();
for (var j = 0; j < restaurants.length; j++) {
L.marker([restaurants[j][7], restaurants[j][8]]).addTo(mymap).on('click', async function () {
document.getElementById('infoName').textContent = await restaurants[j][0].toString();
});
}
}
任何幫助深表感謝!
可能是范圍界定問題。 var
被提升,因此restaurants[j] 實際上是在將 j 增加到restaurants.length 之后使用的。
刪除了異步,因為那里沒有必要。
for (var j = 0; j < restaurants.length; j++) {
let k = j;
L.marker([restaurants[k][7], restaurants[k][8]]).addTo(mymap).on('click', function () {
document.getElementById('infoName').textContent = restaurants[k][0].toString();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.