[英]Storing data in an array using Javascript Prototypical inheritance
做一些JavaScript原型继承,我想在我的Grades constructor
函数中推送参数,并进行存储操作,并使用我的存储方法在this.students
数组中推送数据,然后在其他方法中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);
您的问题出在存储功能内部,起源于定义。
this.studentGrades
实际上定义为数组的长度,而不是数组本身。
如果您不存储输入数组,或者不通过init(inputGrades)
将其传递到storage(inputGrades)
,那么您将无法从存储原型访问原始输入。
更好:将构造函数位更改为:
this.students = [];
this.studentGrades = studentGrades;
并且您在存储内部的功能为:
for(var i=0; i < this.studentGrades.length; i++) {
this.students.push(this.studentGrades[i]);
}
我想你应该还可以。
更新:您的原始函数调用具有可变数量的参数。 完成答案的最简单方法是将参数变量更改为:
var inputGrades = new Grades( [[89,78,93,78], [83,67,93,98], [93,99,73,88]]);
现在,您仅发送一个参数,即数组数组。
备选:将功能更改为
function Grades() { // so no input argument
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = Array.prototype.slice.call(arguments);
this.numRows = 0;
this.numColumns = 0;
然后,您应该能够发送多个参数。
我认为您的代码存在一些问题,尤其是Grades构造函数:
function Grades(studentGrades) {
if(!Array.isArray(studentGrades)) return true;
this.students = [];
this.studentGrades = arguments.length;
this.numRows = 0;
this.numColumns = 0;
this.init();
}
您正在使用数组作为函数的参数,但是您正在传递thtree参数(数组),我认为这行:
var inputGrades = new Grades( [89,78,93,78], [83,67,93,98], [93,99,73,88] );
应该是这样的:
var inputGrades = new Grades( [[89,78,93,78], [83,67,93,98], [93,99,73,88] ]);
接下来的this.studentGrades = arguments.length;
在构造函数中没有用,可能会在您的代码中引起问题,应将其替换为:
this.studentGrades = arguments;
或者,如果您像我一样传递数组,则可以使用:
this.studentGrades = studentGrades;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.