2016-11-03 67 views
1
function studentClasses() { 
    var names = []; 
    var course = []; 
    var sortCourse = []; 
    var uniqueCourse = []; 
    var nameCourse = []; 

    while (records.readNextRecord()) { 
     var studentNames = records.getStudentName(); 
     var studentCourse = records.getStudentCourseNumber(); 

     names.push(studentNames); 
     course.push(studentCourse); 
     sortCourse.push(studentCourse); 
     sortCourse.sort(); 
    } 
    // sort a list of courses to find the unique courses 
    for (var i = 0; i < sortCourse.length; i++) { 
     if (sortCourse[i] !== sortCourse[i - 1]) { 
      uniqueCourse.push(sortCourse[i]); 
     } 
    } 

    uniqueCourse.sort; 
    nameCourse.length = uniqueCourse.length; 

    // create multi-d array containing names for a certain course 
    for (var x = 0; x < uniqueCourse.length; x++) { 
     for (var y = 0; y < course.length; y++) { 
      if (uniqueCourse[x] === course[y]) { 
       nameCourse[x].push(names[y]); 
      } 
     } 
    } 
} 

这是我的代码,我的工作和我收到的推值,并得到一个错误

Uncaught TypeError: Cannot read property 'push' of undefined(…)

错误我有两个阵列(” 当然“&”名称“)包含具有特定索引中的数据的信息。我试图将我的“uniqueCourse”数组中的信息与我的“course”数组进行比较,如果它们匹配,则将使用“course”的索引位置来调用来自“ 名称“。

这里是问题所在: 当我试图推动“名称[Y]”到一个多维数组,将具有等于uniqueCourse(这是5,如果代码是RAN)的长度,我得到错误。

问: 为什么我收到一个未定义的错误,当我尝试使用代码

nameCourse[x].push(names[y]); 

将信息推送到nameCourse其中x是相应级别我希望这些名称被存储?

我想:

nameCourse = [ [however many names called from names[y]], 
       [however many names called from names[y]], 
       [however many names called from names[y]], 
       [however many names called from names[y]], 
       [however many names called from names[y]] ] 

回答

0

nameCourse阵列充满undefined 需要初始化nameCourse [X]是一个数组,然后才推了进去。 类似下面:

nameCourse = new Array(uniqueCourse.length).fill(0);

+0

所以在做这样的事情 nameCourse [X] = [] –

+0

是的。同样的事情 – DanielS

+0

非常感谢你的帮助 –