无法弄清楚如何计算成绩点数

时间:2015-07-10 01:04:10

标签: javascript

试图弄清楚如何将在文本区域中输入的所有字母等级分配到新数组,将字母与点匹配并计算成绩点。就像在这个例子中一样,如何计算totalGradePoints。 HTML部分被削减。任何帮助表示赞赏。

<html>
<!-- gpa2.html  -->

<html>
<head>
    <title>GPA</title>
</head>
<script type="text/javascript">
    //Assigning grades to match points
    var grades = ['A', 'B+', 'B', 'C+', 'C', 'D', 'F', 'AF', 'WF'],
        points = [4, 3.5, 3, 2.5, 2, 1, 0, 0, 0];

    function getData() {
        var input = 0,
            results = [];

        input = document.getElementById("inputs").value.split("\n");
        for (var i = 0; i < input.length; i++) {
            input[i] = input[i].split(" ");
            results.push({
                course: input[i][0].trim(),
                grade: input[i][1].trim,
                creditHours: parseInt(input[i][2], 10)
            });
        }
        return results;
    }

    //GPA calculation
    var output = function() {
        var results,
            totalCreditHours = 0,
            totalGradePoints = 0,
            gpa = 0;

        results = getData();

        for (i = 0, j = results.length; i < j; i++) {
            totalCreditHours += results[i].creditHours;
        }
        gpa = (totalCreditHours === 0 ? 0 : totalGradePoints / totalCreditHours).toFixed(3);

        var output1 = document.getElementById("totalGradePointsOutput");
        output1.value = totalGradePoints
        var output2 = document.getElementById("totalCreditHours");
        output2.value = totalCreditHours
        var output3 = document.getElementById("gpaOut");
        output3.value = gpa
    }
</script>

<body>


</body>
</html>

1 个答案:

答案 0 :(得分:0)

从文本字段中获取值,获得点数组中grade数组上字母的相应索引,并将其附加到另一个名为currentGrades的数组中;

<!Doctype html>
<html>
<body>
Letter Grade <input type="text" id="letterGrade" value="C">
<button onclick="calculateGrade()">Add</button>

<script>
var grades = ['A', 'B+', 'B', 'C+', 'C', 'D', 'F', 'AF', 'WF'],
        points = [4, 3.5, 3, 2.5, 2, 1, 0, 0, 0];

var currentGrades = [];
function calculateGrade() {
    var letter = document.getElementById("letterGrade").value;
    for (var i=0; i<grades.length; i++) {
        if (grades[i] == letter) {
            currentGrades.push(points[i]);
        }
    }
    console.log(currentGrades);
}
</script>
</body>
</html>