调试javascript代码计算平均值然后分配字母等级

时间:2014-02-04 19:27:41

标签: javascript

我正在尝试计算var 1的值的平均值和dbase表中var 2的值的平均值。我还想为平均分配一个字母等级。我的脚本假装它正在工作,甚至在输出中分配字母等级,但计算不正确。你能帮我调试吗?

var correspondence = "FDCBAA"; // last A is for a perfect 5
var courtesyVal = 0, overallVal = 0;    

if (data.length) {
    for (var i = 0; i < data.length; i++) {
        courtesyVal += data[i].grade_courtesy;
        overallVal += data[i].grade_overall;
    }

    courtesyVal = (courtesyVal / data.length);
    overallVal = (overallVal / data.length);
}

courtesyVal = correspondence[Math.floor(courtesyVal)];
overallVal = correspondence[Math.floor(overallVal)];

if (courtesyVal >= 4 || overallVal >= 4) {
    courtesyVal = "A";
    overallVal = "A";
} 
else if (courtesyVal >= 3 || overallVal >= 3) {
    courtesyVal = "B";
    overallVal = "B";
} 
else if (courtesyVal >= 2 || overallVal >= 2) {
    courtesyVal = "C";
    overallVal = "C";
} 
else if (courtesyVal >= 1 || overallVal >= 1) {
    courtesyVal = "D"; 
    overallVal = "D";
} 
else {
    courtesyVal = "F"; 
    overallVal = "F";
}
Appery("courtesy_grade").text(courtesyVal);
Appery("overall_grade").text(overallVal);

1 个答案:

答案 0 :(得分:0)

看起来问题在于您的行:

courtesyVal = correspondence[Math.floor(courtesyVal)];
overallVal = correspondence[Math.floor(overallVal)];

将字符串值分配给变量courtesyValoverallVal

这没关系,但是在这些行下方检查这些值是否等于0到5之间的数字。要解决此问题,您可以将上面两行更改为:

courtesyVal = Math.floor(courtesyVal);
overallVal = Math.floor(overallVal);

或者您可以删除所有if语句,因为您设置courtesyValoverallVal的方式正确地获取'correspondence'值。

以下是一些示例数据和第二个选项:Click here

如果这不是你想要的,我很乐意再试一次!