无法将特定对象属性推送到数组中

时间:2014-10-05 02:09:26

标签: javascript arrays

我试图将学生对象的所有属性推送到一个包含学生对象的数组中。我的所有属性都保存了一个,这是一个包含字符串数组的属性被推入学生数组中,我不知道为什么。当我尝试将包含该数组的(第一个)元素打印到控制台时,它表明它是未定义的。这是我到目前为止的代码:

var person = { firstname: "", lastname: "", email: "" };
function Student(){};
Student.prototype = person;
Student.prototype.sid = "";
Student.prototype.courses = [];
var students = [];



var answer = null;

function getstudents(answer, students){
    var teststudent = new Student;
    for(var i = 0; i < answer.length; i++) {
        if (i < 4) {
            teststudent[i] = answer[i];

        }
        if(i > 3) {
            teststudent.courses[i] = answer[i];
            console.log(teststudent.courses[i]); //element is defined
        }

    }
    students.push(teststudent);
    console.log("printing ", students[0][4]); //states that the element is undefined
}

function getanswer(string) {
    answer = string;
    return answer;
}



do {
    getanswer(prompt("Please enter your first name, last name, student ID, email and courses (seperated by ',')"));
    if(answer !== ""){
        var array = answer.split(',');
        answer = array;
        getstudents(answer, students);
    } else {
        answer = null;
    }


} while(answer !== null );

1 个答案:

答案 0 :(得分:0)

你的意思是:

teststudent.courses[i-4] = answer[i];