我这里有很多代码......基本上我想将我的全局变量转换为数组...... IE。等级数组。当我提示等级(提示)时,它应该验证输入是一个数字(通过 if 语句),如果它不是一个有效的数字,例如。一个字母,程序返回一个警报(“不是有效的输入,请输入有效的输入”)。我不明白我的代码哪里出错了,但它不断返回警报消息。
这是代码:
// Loop through assignments
for(var k = 1; k <= numberOfAssignments; k++) {
// Print the first <td>
document.write(table.dataopen);
// Get the grade for the assignment
var grades = new Object();
grades.validrange = 0;
grades.min = 0;
grades.max = 100;
var grade = new Array();
do {
grade[grade.length] = prompt("What's the grade for assignment " + k + "?");
var convertedInput = parseInt(grade[grade.length]);
// Using automatic conversion, if the original input and the converted input are the same,
// we know we have a valid integer.
var result = convertedInput == grade[grade.length];
// If not a valid integer, let's show an appropriate error message. We use alert as
// we may change how we report errors back.
if(!result) {
alert("Not a valid input. Please try again");
}
// Note the use of paranthesis; the first three clauses have to be all TRUE in order for the value in
// the paranthesis to be true. In this context, we first check that all values are indeed numbers.
// Then we check whether the grade is less than the min or greather than the max
if((!isNaN(grade[grade.length]) && !isNaN(grades.min) && !isNaN(grades.max)) &&
grade[grade.length] < grades.min || grade[grade.length] > grades.max) {
// Invalid range, so show the error.
alert("Valid ranges are between " + grades.min + " and " + grades.max);
grades.validrange = false;
}
else {
// If we came here, it means we didn't use the previous return, which in turns mean that the three
// arguments are numbers AND the range is valid
grades.validrange = true;
}
} while(!result || !grades.validrange);
var score = parseInt(grade[grade.length]);
// Display the grade
document.write(score);
// Keep track of the grades/scores (add to total)
totalScore += score;
// Print the </td>
document.write(table.dataclose);
}