Array.push causes program to have errors

扶醉桌前 提交于 2019-12-11 16:23:50

问题


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.


回答1:


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'); 
  }
}

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.




回答2:


Do you want to validate entered course code? In such case you need to do it with the item not with the whole array:

while (confirm("...")) {
  var courseCode = prompt("...");

  var upperTest = course.slice(0,3);
  var integerTest = course.slice(4,7);

  if (courseCode.length !== 7) {
    alert ('Invalid Course Code');
    continue;
  }

  // place your other if's here

  courses.push(courseCode);
}


来源:https://stackoverflow.com/questions/12215413/array-push-causes-program-to-have-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!