[英]How do I sort a two dimensional array in JavaScript?
My sorting function at the end isn't working.我最后的排序 function 不起作用。 I want to sort student grades in ascending order but I can't get it to print out.
我想按升序对学生成绩进行排序,但无法打印出来。 My sorting function goes through and manually compares however I can't get it to work.
我的排序 function 经历并手动比较,但我无法让它工作。 The problem may be that the student class is whats being used to add values to the array.
问题可能是学生 class 用于向数组添加值。
<html>
<body>
<script>
class Student {
constructor(name,grade) {
this.name = name;
this.grade = grade;
}
detail() {
document.writeln(this.name + " " + this.grade + "<br/>")
}
}
var grade = [];
var count = 0;
function setStudent() {
var name = prompt("Enter Name", "name");
while(name != '???') {
var grades= parseInt(prompt("Enter Grade", "Grade"));
var student = new Student(name,grades);
grade.push(student);
name = prompt("Enter Name", "name");
count++
}
}
function showGrades() {
for(i=0;i<count;i++) {
grade[i].detail();
}
}
function maxGrade() {
var mgrade = grade[0].grade;
var names = "";
for (i=0;i<count;i++) {
if(mgrade<grade[i].grade) {
mgrade=grade[i].grade;
names = grade[i].name
}
}
document.writeln("Max Grade: " + mgrade + " Name: " + names);
}
setStudent();
showGrades();
maxGrade();
document.writeln("<br/> Assorted List (Ascending): <br/>");
grade.sort(function(a,b) {
return a[0] - b[0] || a[1] - b[1];
});
console.log(grade);
</script>
</body>
</html>
The problem is this statement:问题是这样的声明:
grade.sort(function(a,b) {
return a[0] - b[0] || a[1] - b[1];
});
a
and b
are Student objects. a
和b
是学生对象。 It shows that right in your console.log
statement.它在您的
console.log
语句中显示了这一点。 So, a[0]
and b[0]
are undefined.所以,
a[0]
和b[0]
是未定义的。
I am not sure what a[1] - b[1]
refers to, but I think you want this:我不确定
a[1] - b[1]
指的是什么,但我认为你想要这个:
grade.sort(function(a,b) {
return a.grade - b.grade;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.