[英]JavaScript how to ensure user enters a number between 1 and 100
您好,我希望用户输入一个介于1到100之间的数字,或者更高,我希望它显示数组超出范围,而不是将数字添加到数组中,这是我所拥有的,并且可以,但是当您输入另一个数字时,它说NAN
for(var i = 0; Repeat !== 'n'; i++){
Student.push(prompt("Enter Student Name: "));
Mark.push(parseInt (prompt("Enter Student mark: ")));
//Check if Mark entered is not out of bounds and gives a grade
if (Mark[i] <0 || Mark[i] >100){
alert("Grate out of bounds");
Mark.splice(i);//Removes array if out of bounds
}else if (Mark[i] >= 83){
getGrade.push("A");
A++;
}else if (Mark[i] >= 70){
getGrade.push ("B");
B++;
}else if (Mark[i] >= 50){
getGrade.push ("C");
C++;
}else if (Mark[i] >= 0){
getGrade.push ("F");
F++;
//If mark is not a number
}else if (isNaN(Mark)){
alert("Must input numbers");
}
Repeat = prompt ("Do you want to enter another student: y/n");
}
输入不正确的值时,数组将不再与i
同步。 例如,如果您为一年级输入( Bob
和1000
),请考虑在调用Mark.splice(i)
之后存储到变量中的内容:
Student = [Bob]
Mark = []
现在Mark
是空的, i
已经增加到1
。 假设您现在输入值Johnny
和50
。 您的变量如下所示:
Student = [Bob, Johnny]
Mark = [50]
请注意,当您的代码验证成绩时,没有Mark[1]
,因为该数组仅包含一个值,而i
正在查看第二个条目-因此是NaN
。 此外,与在Mark
相比,您在Student
条目更多。
作为一般原则,在完成所有验证逻辑之前,您不应“提交”数据。 因此,将输入的数量存储在临时变量中,进行检查,然后在拥有良好输入数据后最终将它们最后添加到数组中:
var entryStudent = prompt("Enter Student Name: ");
var entryMark = parseInt (prompt("Enter Student mark: "));
//Check if Mark entered is not out of bounds and gives a grade
...
//Once you have determined the values are valid, add them to the array
if (valid) {
Student.push(entryStudent);
Mark.push(entryMark);
} else {
// make sure i is moved back to previous entry so you don't skip one
i--;
}
这段代码并不完整(例如,您需要弄清楚如何确定valid
是true
还是false
),但是它应该可以为您提供总体思路。
我建议两件事-
在进行其他任何检查之前,请进行“ isNaN”检查(这样就不会插入错误的值)。
将parseInt结果存储在一个变量中,对该变量进行所有检查,并且只有在它通过的情况下,才能将其压入Marks中 。 这样,您可以避免持有i参考。
像这样:
var grade, name;
for (var i = 0; Repeat !== 'n'; i++) {
name = prompt("Enter Student Name: ");
grade = parseInt(prompt("Enter Student mark: "));
// check if grade entered is a number
if (isNaN(grade)) {
alert("Must input numbers");
continue;
}
// check if grade entered is not out of bounds
if (grade < 0 || grade > 100) {
alert("Grade out of bounds");
continue;
}
// store the data
Student.push(name);
Mark.push(grade);
if (grade >= 83) {
getGrade.push("A");
A++;
} else if (grade >= 70) {
getGrade.push("B");
B++;
} else if (grade >= 50) {
getGrade.push("C");
C++;
} else if (grade >= 0) {
getGrade.push("F");
F++;
}
Repeat = prompt("Do you want to enter another student: y/n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.