问题描述
我按照上一个问题的建议让我的提示向数组添加值,但是这导致我的程序在没有True值时抛出它们。
I followed the advice from a previous question to get my promps to add values to an array, but it has caused my program to throw up True values when they are not.
HIGHEST_GRADE = 7;
LOWEST_GRADE = 0;
var course = new Array();
var grade = new Array();
while(confirm("Would you like to add a course?")){
course.push( prompt("Enter the course code. Example - ABC1234") );
};
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
if (isNaN(grade)) {
alert('Invalid Grade');
}
if (LOWEST_GRADE > grade || HIGHEST_GRADE < grade) {
alert('Invalid Grade');
}
我将其设置为确保输入的文本符合条件,但是由于
I have it set to make sure the entered text matches the conditions, but since the .push was added the whole thing stuffs up.
我收到无效的课程代码错误,有些东西正在起作用。
I get an Invalid Course Code error, something is playing up with that.
推荐答案
Array
用于存储多个课程,这很好。但是,由于它是一个数组,因此需要使用循环访问它的每个位置以验证每个个人课程:
The Array
is used to store multiple courses, which is fine. But, since it's an array, you need to access each position of it to validate each individual course, using a loop:
var courses = new Array(); // use the name courses instead, to indicate that it's a collection
for (var i = 0; i < courses.length; i++) {
var course = courses[i];
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
}
这将验证每个课程
位于 Array
中。否则,当您测试 courses.length
时,您将验证数组中元素的数量,而不是每个课程的字符数
This will validate every course
that is in the Array
. Otherwise, when you test courses.length
, you'll be validating the number of elements in the array, not the number of characters of each course.
对于成绩
数组也需要执行相同的操作。
The same needs to be done for the grades
array.
这篇关于Array.push导致程序出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!