我这里有很多代码..基本上我想将全局变量转换为数组... IE。等级数组。当我提示等级(提示)时,它应该验证输入是一个数字(通过if语句),如果它不是有效数字,例如。一个字母,程序返回一个警报(“不是有效的输入,请输入有效的输入”)。我不明白我的代码在哪里出错,但是KEEPS会返回警报消息。
以下是代码:
// 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);
}
答案 0 :(得分:2)
grade[grade.length]
&lt; ~~我这里的问题就是问题。
grade.push()
- 在评分中添加新的输入消息。grade[grade.length - 1]
- 获取最后一个-
//...
grade.push(prompt("What's the grade for assignment " + k + "?"));
var lastIndex = grade.length - 1;
// Using automatic conversion, if the original input and the converted input are the same,
// we know we have a valid integer.
var convertedInput = parseInt(grade[lastIndex]);
//...
答案 1 :(得分:0)
这是你的问题
grade[grade.length] = prompt("What's the grade for assignment " + k + "?");
var convertedInput = parseInt(grade[grade.length-1]);
您的第一个声明正常。假设您的数组有一个元素,grade.length
将返回1,这将是您下一个元素的索引。但在第二个语句中,grade.length
将为2,而等级[2]未定义,因为您的数组只有两个元素(等级[0]和等级[1])。所以你的第二个陈述应该是
var convertedInput = parseInt(grade[grade.length-1]);
答案 2 :(得分:0)
grade.length在初始化后为0,然后在添加元素后变为1。 它应该是:
var convertedInput = parseInt(grade[grade.length - 1]);
答案 3 :(得分:0)
var result = isNaN(convertedInput)
结果,请使用parseInt