当我想使用二维数组时 returns 我未定义

When i want to use 2 dimensional array it returns me undefined

我使用我输入的数据库。

我声明了数组并想在第一个数组中压入另一个数组。

当我尝试使用二维数组时,控制台返回 undefined

let dataAboutCovid = [];
let date, totalCases, todayCases, recovered;
let country = "USA";

//Read file from input
//Control if country exist
//Put data about covid in dataAboutCovid

function readFile(input) {
  let database;

  for (i = 0; i < input.files.length; i++) {

    let reader = new FileReader();
    reader.readAsText(input.files[i]);

    reader.onload = function(e) {
      database = e.target.result;

      let arrayOfCountry = database.split(`\n`).find((item) => item.includes(country))
      if (!arrayOfCountry) {
        return
      }
      if (arrayOfCountry.slice(0, 3) == ",,,") {
        date = arrayOfCountry.slice(3, this.length).split(",")[1].split(" ")[0];
        totalCases = arrayOfCountry.slice(3, this.length).split(",")[4];
        todayCases = arrayOfCountry.slice(3, this.length).split(",")[5];
        recovered = arrayOfCountry.slice(3, this.length).split(",")[6];
        dataAboutCovid.push([date, totalCases, todayCases, recovered]);
      }
    }
  };

  console.log(dataAboutCovid[1][1])
}

我看到两个问题。

  • i为0时,只填dataAboutCovid[0],所以dataAboutCovid[1]未定义
  • 由于js的异步特性,有可能console.log先于reader.onload执行。

我认为您正在尝试读取一堆文件而不是一个文件并在拆分换行符上迭代