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(…)
我有两个数组(“类(class)”和“名称”),其中包含特定索引中包含数据的信息。我正在尝试将“uniqueCourse”数组中的信息与“course”数组进行比较,如果它们匹配,则“course”中的索引位置"然后将用于从“names”中的索引位置调用信息。
问题出在这里: 当我尝试将“names[y]”插入长度等于 uniqueCourse(如果运行代码则为 5)的多维数组时,出现错误。
问题: 为什么当我尝试使用代码时会收到未定义的错误
nameCourse[x].push(names[y]);
将信息从names推送到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]] ]
最佳答案
您的 nameCourse
数组已填充 undefined
您需要将 nameCourse[x] 初始化为数组,然后才将其插入其中。
如下所示:
nameCourse = new Array(uniqueCourse.length).fill(0);
关于javascript - 将一个数组中的值插入多维数组并出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40410631/