Javascript 程序不断输出错误的数组索引

标签 javascript arrays alert

我正在努力完成一项作业,但我卡住了,找不到解决方案。 以下是我的完整代码。

//Student Object
        var student = {
          f_name: "",
          l_name: "",
          s_numb: "",
          email: "",
          courses: [],
          /*This function returns if current object has a specific course 
          and returns true if it does and false if not.*/
          hasCourse: function (course) {
            for (var c = 0; c < this.courses.length; c++) {
              if (course == this.courses[c]) {
                return true;
              }
            }
            return false;
          }
        };
        
        
        /*This function returns name with first letter 
        capitalized and the rest lowercase.*/
        function formatingName(name) {
          return name.charAt(0).toUpperCase() + name.substr(1, name.length);
        }
        
        /*This function validates to match the Student ID pattern and 
        returns true it matches and false if not.*/
        function validateStudentID(sid) {
          var patt = /^([0-9]{3}[.]){2}[0-9]{3}$/;
          return patt.test(sid);
        }
        
        /*This function receives a string array of course codes which 
        are to be registered for a student. The function returns an empty 
        string indicating all course codes in the array are valid; otherwise 
        the function returns the first invalid course code in the array.*/
        function validateCourses(courses) {
        
          var error = false;
        
          for (i = 0; i < courses.length; i++) {
            if (error == false) {
              if (courses[i] != "APC100" && courses[i] != "IPC144" && 
                courses[i] != "ULI101" && courses[i] != "IOS110" && 
                courses[i] != "EAC150" && courses[i] != "IBC233" && 
                courses[i] != "OOP244" && courses[i] != "DBS201" && 
                courses[i] != "INT222") {
                error = courses[i];
                break;
              }
            }
          }
          if (error != false) {return error;} else {return "";}
          return '';
        }
        
        
        var response = true; //Continues to prompt if error is true
        var error = false;   //Error flag
        var temp_obj = [];   //Temporary object that hold current object's values
        var temp_course = []; 
        var students = [];
        var x = 0;
        
        while (response == true) {
        
          do {
          
            var str = prompt("Please enter first name, last name, student ID,\nemail and courses (separated by ',')");
            
            if (str == "" || str === null) {
              response = false;
              break;
            }
        
            //Removing white spaces in the string
            str = str.split(' ').join('');
            //Splitting the string into array by , (coma) and assigning it to temporary object array
            temp_obj = str.split(',');
        
            //Validating Student ID
            if (validateStudentID(temp_obj[2]) == false) {
              alert(temp_obj[2] + " is not a valid student ID, Please use xxx.xxx.xxx format.\nPlease try again!");
              error = true;
            }
            //Validating if student is registered in atleast 1 course.
            if (temp_obj.length < 5) {
              alert("A student must be registered in at-least 1 course");
              error = true;
            }
            //Checking if student is registered in more than 6 courses
            if (temp_obj.length > 10) {
              temp_obj = temp_obj.slice(0,9);
            }
            //Extracting courses from temporary object array
            temp_course = temp_obj.slice(4, temp_obj.length);
        
            //Makking all the courses uppercase
            for (i = 0; i < temp_course.length; i++) {
              temp_course[i] = temp_course[i].toUpperCase();
            }
            //Validating if courses are valid
            if (validateCourses(temp_course) != "") {
              alert(validateCourses(temp_course) + " is not the course provided by CPD program!\nPlease try again.");
              error = true;
            }
        
          }
          while (error == true);
          //Break out of loop if user submitted nothing or if user pressed cancel
          if (response == false) {break;}
        
            //Merging cources array back with temporary object array
            temp_obj = temp_obj.concat(temp_course);
        
            //Creating a new instance of a student    
            students[x] = Object.create(student);
            
            //Assigning values to student object from temporary object;
            students[x].f_name = formatingName(temp_obj[0]); //Formatting name
            students[x].l_name = formatingName(temp_obj[1]);
            students[x].s_numb = temp_obj[2];
            students[x].email = temp_obj[3].toLowerCase(); //Making the email all lowercase
            
            //Making the course codes in Uppercase
            for (i = 0; i < (temp_obj.length) - 4; i++ ) {
              students[x].courses[i] = temp_obj[i + 4].toUpperCase();
            }
          
          x++;
        
        }
        
        //Printing total registered students
        alert("There are total " + students.length + " students registered.");
        
          var R_fname = [];
          var R_lname = [];
          var R_sid = [];
          var R_email = [];
        
        do {
          var no_error = false;
          var query = true;
          var query_course = [];
        
          while (no_error == false) {
            query = prompt("Please enter a course code:");
            if (query == "" || query == null) {
              query = false;
              break;
            }
        
            no_error = true;
        
            query_course[0] = query.toUpperCase();
        
            if (validateCourses(query_course) != "") {
              alert(query + " is not the course provided by CPD program!\nPlease try again");
              no_error = false;
            }
        
          }
        
          if (query == false) {break;}
        
        
          //THIS IS WHERE I THINK THE PROBLEM IS
          //THIS IS WHERE I THINK THE PROBLEM IS
          //THIS IS WHERE I THINK THE PROBLEM IS
          //THIS IS WHERE I THINK THE PROBLEM IS
        
          for (var a = 0; a < students.length; a++) {
        
            //Checking if student is registred in a course
            if (students[a].hasCourse(query_course) == true) {
              //Assigning values to temporary array.
              R_fname[a] = students[a].f_name;
              R_lname[a] = students[a].l_name;
              R_sid[a] = students[a].s_numb;
              R_email[a] = students[a].email;
         
            }
          }
        
          var fin_str = "";
        
          //Concatenating all the students in a specific course to fin_str as string.
          for (var b = 0; b < R_fname.length; b++) {
            fin_str += (R_fname[b] + " " + R_lname[b] + "    " + R_sid[b] + "    " + R_email[b] + " \n");
          }
        
          //Printing list of student in a specific course
          alert("List of students registered in " + query + "\n\n" + fin_str);
        
          //Retting temporary arrays
          R_fname.length = 0;
          R_lname.length = 0;
          R_sid.length = 0;
          R_email.length = 0;
        
          //Confirms to Exit the query loop
          if (confirm("Click 'OK' to continue to query class lists.\nClick 'Cancel' to stop the program.") == false) {break;}
        
        }
        while (query != false);

这些是测试值:

罗伊, bean ,056.171.486,rbean@example.ca,int222

卡尔,贝尔,121.126.536,cbell@example.ca,dbs201,int222

eric,brand,046.123.976,ebrand@example.ca,oop244,dbs201,int222

亨利,粘土,034.146.412,hclay@example.ca,ibc233,oop244,dbs201,int222

当程序要求输入类(class)代码时;它应该查看学生是否有该类(class),只有在有的情况下,它才会打印学生信息。

在我的例子中,即使学生没有类(class),它仍然会打印出来。 请运行代码,看看它是否更有意义……我无法解释得更好

最佳答案

问题可以简化为:

var Foo = {
  courses: []
};

var x = Object.create(Foo);
var y = Object.create(Foo);
x.courses.push(123);
alert(y.courses[0]); // "123"

此行为的原因是两个对象都继承了相同的原型(prototype),并且对.courses 所做的任何更改都将应用于两个对象。

因此,最好创建一个构造函数:

function Foo()
{
    this.courses = [];
}

var x = new Foo();

关于Javascript 程序不断输出错误的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30993325/

相关文章:

javascript - 如何使用查询中不存在的值列表填充选择元素

c++ - 运行时边界数组的源级检测有多难?

swift - 从 Swift 异常生成错误表

android - 收到消息时,Urban Airship 通知不会显示在 Android 设备中

javascript - 如何使用office js检测设备/应用程序

javascript - 为什么我的计算器中的功能无法正常工作?

javascript - 如何从数组中获取前N个元素

比较 char 数组元素

JavaScript 警报不起作用

javascript - 将匿名函数中的 javascript 与 gulp 连接起来