繁体   English   中英

未捕获(承诺中)类型错误:无法读取未定义的属性“0”。 从 csv 文件中提取以填充数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM