javascript - 返回全局数组元素
问题描述
我试图简单地打印出我从 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);
}
解决方案
问题似乎是您尝试从函数中获取索引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);
推荐阅读
- excel - Excel 2016 vba 宏将边框设置为内部过滤单元格的单元格范围会产生错误(使用 Excel 2013 一切都很好)
- html - 将 HTML + CSS 添加到 wix
- php - 生成 Symfony4 PDF 但有 HTTP500
- python - Aiokafka 库不会异步消费消息
- c++ - C++ 中容器的 decltype、通用引用和转发
- java - 将图像从图像视图保存到设备
- ruby-on-rails - 用户中没有方法错误#show undefined method `following' for User
- javascript - 如何使用angularJS在mongodb中上传base64中的图像
- ios - 如何使用多个目标使用具有相同名称的不同资产
- php - 使用 php mysqli 创建账本并根据 DR 和 CR 获取余额