【发布时间】:2015-10-01 15:56:33
【问题描述】:
做一些 javascript 原型继承,我想在我的 Grades constructor 中推送参数并进行存储操作,并使用我的存储方法将数据推送到我的 this.students 数组中,然后在我喜欢的范围内使用这些值我的其他方法。
但问题是,当我在控制台记录构造函数时,它会按照我需要的方式将数据推送到 this.students 数组中,但每个对象都显示为未定义。
这很奇怪,因为如果我在 Grades constructor 内运行 for 循环,它将完美运行。但我想有一个单独的方法来做到这一点,在我的Grades constructor
任何能帮我指出正确方向的帮助都会很棒!谢谢!
function Grades(studentGrades) {
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = arguments.length;
this.numRows = 0;
this.numColumns = 0;
this.init();
}
/*
* Method to initialize functions
*/
Grades.prototype.init = function() {
this.storage();
};
/*
* Method to store a list of grades in an array object
*/
Grades.prototype.storage = function() {
for(var i=0; i < this.studentGrades; i++) {
this.students.push(this.studentGrades[i]);
}
};
/*
* Method to add grades
*/
Grades.prototype.addGrades = function(numRows, numColumns, initial) {
for(this.numRows; this.numRows < this.students.length; this.numRows++ ) {
}
};
/*
* Method to display the students average
*/
Grades.prototype.display = function() {
// body...
};
var inputGrades = new Grades( [89,78,93,78], [83,67,93,98], [93,99,73,88] );
console.log(inputGrades);
【问题讨论】:
-
@Teemu 我的论点的长度是 3 在这种情况下 var inputGrades = new Grades( [89,78,93,78], [83,67,93,98], [93, 99,73,88])。就像在函数内部传递对象一样,希望操纵我放在 Grades 函数中的任何 arguments.length 的数据。
-
你设置
this.studentGrades = arguments.length;(即3*),然后你使用this.studentGrades作为一个数字,然后一行你认为它是一个数组??? *)arguments是一个类似数组的对象,包含传递给函数的参数。 -
@Teemu 很好,如果你 console.log(this.studentGrades) 它的长度是 3
-
@Amechi 呃,我的错,你传递了三个参数......但是
this.studentGrades不能同时是一个数字和一个数组。
标签: javascript arrays function constructor arguments