首页 > 解决方案 > 返回全局数组元素

问题描述

我试图简单地打印出我从 csv 文件导入的学生的全局数组列表。我已经完成了足够多的故障排除,以知道数据正在被导入并正常读取。常见的答案似乎是您不需要全局数组的“var”声明,但这对我也不起作用。

这里是我的报关表:

//Student array list from csv import
 studentList = []; 
//window.studentList = [];

这是我初始化数组的地方:

function processData(csv){
let allLines = csv.split(/\r\n|\n/); 

for(let i = 0; i < allLines.length; i++)
{
    let row = allLines[i].split(",");
    let col = []; 

    for(let j = 0; j < row.length; j++)
    {
       col.push(row[j]);  
    }
    if(col == " ") break;
    studentList.push(col);
}

//when I alert the array element by element the data is being read from within this function 
for(let i =0; i < studentList.length; i++)
{
    alert(studentList[i]);
}
}

但是,如果我要使用 get 方法返回元素,我会得到一个“未定义”错误

function getStudent(index) {
     return studentList[index];
}

for(let i = 0; i < studentList.length; i++)
{
      alert(getStudent[i]);
}

编辑:尽管该解决方案是正确的,但从另一个函数调用时我仍然遇到同样的问题。例如,在下面我需要为每个未定义的学生返回旅行出发。

function getStudentsDeparture(i)  
{
    trip.departure = getStudent(i);
    alert(trip.departure);          //prints undefined

    trip.destination = "123 Smith Rd, Maddingley VIC 3340"; 
    console.log('dest is: ' + trip.destination + ' dept is: ' + 
    trip.departure);
 }

标签: javascriptarraysglobal

解决方案


问题似乎是您尝试从函数中获取索引getStudent[i]。尝试将该行更改为alert(getStudent(i));带括号。

编辑 我用这段代码测试过,它对我来说很好

studentList = [];

studentList.push('student1');

function getStudent(index) {
    return studentList[index];
}

function getStudentsDeparture(i) {
    var student = getStudent(i);
    alert(student);
}

getStudentsDeparture(0);

推荐阅读