javascript如何在数组中的对象属性上使用排序功能

时间:2017-05-01 16:20:52

标签: javascript

我有一个使用对象数组的javascript程序。该对象有3个属性。其中一个是成绩。我试图访问该对象的属性并使用sort函数来获取用户输入的最大和最小分数。无法理解如何访问此字段并在其上使用.sort函数。这就是我所拥有的:

var studentArr = [];

  function Student(name, grade, id) {
  this.name = name;
  this.grade = grade;
  this.id = id; 
}

function summ() {

        var namip = document.getElementById("inp").value;
        var gradip = document.getElementById("inps").value;
        var idip = document.getElementById("inpsid").value;

        var nwStudent = new Student(namip, gradip, idip);
        var grade;
        var average;
        var totalc;
        var sum = 0;

            for (i = 0; i < studentArr.length; i++) {
                sum += parseInt(studentArr[i].grade);
            }
            average = sum / nwStudent.grade.length;
            document.getElementById("aop").innerHTML ="Average score: <br>" + average;

        if (gradip.valueOf() == 70) {

                grade = "C";
                document.getElementById("opo").innerHTML = grade;
        }

        if (gradip.valueOf() == 80) {

                grade = "B";
                document.getElementById("opo").innerHTML = grade;
        }

        if (gradip.valueOf() == 90) {

                grade = "A";
                document.getElementById("opo").innerHTML = grade;
        }

        for(i=0; grade == "C"; i++)
        {
            totalc = totalc + i;
        }

    //  document.getElementById("cop").innerHTML = totalc; 

        studentArr.sort(function(a, b){return b-a});
        document.getElementById("hop").innerHTML = "Max Score is: <br>" + studentArr[0];

        studentArr.sort(function(a, b){return a-b});
        document.getElementById("lop").innerHTML = "Min Score is: <br>" + studentArr[grade];

    }

</script>

1 个答案:

答案 0 :(得分:0)

sort函数会传入两个学生对象,因此您需要返回其.grade属性的比较。

studentArr.sort(function(a, b){return b.grade-a.grade});