使用Javascript prototype继承在数组中存储数据

Storing data in an array using Javascript Prototypical inheritance

本文关键字:存储 数据 数组 Javascript prototype 继承 使用      更新时间:2023-09-26

做一些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);

我认为你的代码有一些问题,特别是与等级的构造函数:

function Grades(studentGrades) {
    if(!Array.isArray(studentGrades)) return true;
    this.students = [];
    this.studentGrades = arguments.length;
    this.numRows = 0;
    this.numColumns = 0;
    this.init();
}

你正在使用一个数组作为函数的参数,但你正在传递三个参数(数组),我认为这一行:

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;

您的问题在您的存储函数内部,源自定义。

this.studentGrades实际上定义为数组的长度,而不是数组本身。

如果您不存储输入数组或将其通过init(inputGrades)传递给storage(inputGrades),则无法从存储原型访问原始输入。

更好:将构造函数bit改为:

this.students = [];
this.studentGrades = studentGrades;

和你的函数在存储到:

for(var i=0; i < this.studentGrades.length; i++) {
    this.students.push(this.studentGrades[i]);
}

我想你会没事的。

UPDATE:您的原始函数调用具有可变数量的参数。获得完整答案的最简单方法是将参数变量更改为:

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;

然后你应该可以发送多个参数