2

I am trying to simply print out a global array list of students that I have imported from a csv file. I've done enough troubleshooting to know that the data is being imported and read fine. The common answer seems to be that you don't require a "var" declaration for a global array but this wasn't working for me either.

Here is my declaration:

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

This is where I initialize the array:

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]);
}
}

But if I was to use a get method to return the elements I would get an 'undefined' error

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

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

EDIT: Despite that solution being right, I still have the same issue when calling from another function. For example in the following I need to return the trip departure for each student which is undefined.

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);
 }

1 Answer 1

3

The issue seems to be that you try to get an index from the function getStudent[i]. Try change that row to alert(getStudent(i)); with parenthesis.

EDIT I tested with this code and it works fine for me

studentList = [];

studentList.push('student1');

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

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

getStudentsDeparture(0);
Sign up to request clarification or add additional context in comments.

2 Comments

You are right, but when still when I try from a separate function I am still getting undefined.
@Stefan Are you sure that the index is within range of studentList array?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.