简体   繁体   English

使用 Javascript 在构造函数中使用数组

[英]Using an array inside a constructor using Javascript

I've been trying to find a way to correctly define an array as one of the constructor values.我一直试图找到一种方法来正确地将数组定义为构造函数值之一。 Let's say we have a student and we need to have an array with his grades and then using the array we need to get an average from the student's grades.假设我们有一个学生,我们需要有一个包含他成绩的数组,然后我们需要使用该数组从学生的成绩中获得平均值。 Sadly, I only found some threads addressing this in other programming languages.遗憾的是,我只发现一些线程在其他编程语言中解决了这个问题。 This is what I thought would work:这就是我认为会起作用的:

function student(name, surname, number, grades) {
this.name = name;
this.surname = surname;
this.number = number;
this.grades = [];
this.average = function(grades) {
 var sum = 0;
 for(var i = 0; i < grades.length; i++) {
  sum + = grades[i];}
  var average = sum / grades.length;
  return average;
 }
}

And then进而

var student1 = new student("Peter","Cat",14444,[2,3,4]);
console.log(student1);

Unfortunately, it shows my grades array as blank and I can't see if my average function is working properly.不幸的是,它显示我的成绩数组为空白,我看不到我的平均功能是否正常工作。 Which part(s) should I change so that I would actually have some values in the grades array?我应该更改哪个部分,以便我实际上在成绩数组中有一些值?

Thank you.谢谢你。

You have a couple things messed up.你有几件事情搞砸了。 If you are going to pass the grades array in as an argument, then you need to set grades with this:如果您要将 grades 数组作为参数传递,则需要使用以下内容设置成绩:

this.grades = grades;

Also in the average function you need to refer to grades with this.grades not just grades.同样在平均功能中,您需要使用this.grades来引用成绩,而不仅仅是成绩。 This will allow you to add more grades later and still get the correct average.这将允许您稍后添加更多成绩并仍然获得正确的平均值。 You could also consider making the grades optional by defining the constructor with something like:您还可以考虑通过使用以下内容定义构造函数来使成绩可选:

function student(name, surname, number, grades =[])

Then if you don't pass in a value, an empty array will be waiting for you.然后如果你不传入一个值,一个空数组会等着你。

In the end you might have something like:最后你可能有这样的事情:

 function student(name, surname, number, grades = []) { this.name = name; this.surname = surname; this.number = number; this.grades = grades; this.average = function() { return this.grades.reduce((a, c) => a + c, 0) / this.grades.length } } var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]); console.log("Average: ", student1.average()) // add another grade: student1.grades.push(6) console.log("New Average: ", student1.average() )

You can solve same problem by using ES6, in your code, you are initializing this.grade=[] with an empty array inside function so further processing of average will be done on empty array only.您可以使用 ES6 解决同样的问题,在您的代码中,您正在使用函数内部的空数组初始化this.grade=[] ,因此仅对空数组进行平均值的进一步处理。 For good practice, function parameters should be assigned with a default value, so that if mistakenly we do not pass an array as an argument then the function parameter will use the default value.为了良好的实践,函数参数应该被分配一个默认值,这样如果我们错误地没有将数组作为参数传递,那么函数参数将使用默认值。 Attaching code snippet for easy understanding in ES6.附上代码片段以便于在 ES6 中理解。

class std{
constructor(name, surname, number, grades = []) {
    this.name = name;
    this.surname = surname;
    this.number = number;
    this.grades = grades;
}  

average() {
  if(this.grades.length !== 0){
    return this.grades.reduce((previous, current) => previous + current, 0) / 
    this.grades.length
  } else { return "no grades mentioned"; }
 }
}

var student1 = new std("Peter", "Cat", 14444, [1, 3, 4]);
console.log("Average: ", student1.average());
//add new student
var student2 = new std("Prasanna", "sasne", 14444);
console.log(student2); 

//student2.grades.push(7)
//console.log("New Average: ", student2.average() )

You're already passing grades into the student() function, so you don't need to pass it in to the student.average function (as the inner function will already have access to the outer function parameter).您已经将grades传递给student()函数,因此您无需将其传递给student.average函数(因为内部函数已经可以访问外部函数参数)。 Because of this, you also don't need to set this.grades = [] .因此,您也不需要设置this.grades = []

Also, sum + = grades[i] should be sum += grades[i] .此外, sum + = grades[i]应该是sum += grades[i]

Simply fixing this error, then omitting passing grades into the inner function will correctly show the average, as can be seen in the following:简单地修复这个错误,然后在内部函数中省略及格grades将正确显示平均值,如下所示:

 function student(name, surname, number, grades) { this.name = name; this.surname = surname; this.number = number; this.average = function() { var sum = 0; for (var i = 0; i < grades.length; i++) { sum += grades[i]; } var average = sum / grades.length; return average; } } var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]); console.log(student1.average());

Your initialization of the variable is an empty array.您对变量的初始化是一个空数组。

this.grades = [];

Should be应该

this.grades = grades;

However, I recommend that you study some javascript ES6 / ECMAScript 2015 and use classes.但是,我建议您学习一些 javascript ES6 / ECMAScript 2015 并使用类。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

class Student {
  constructor(grades) {
    //... Other code
    this.grades = grades;
  }
}

you can use this line :你可以使用这一行:

function student(name, surname, number, grades){ }函数学生(姓名,姓氏,数字,成绩){}

instead of this:而不是这个:

function student(name, surname, number, grades = [ ]){ }函数学生(姓名,姓氏,数字,成绩= [ ]){ }

 function student(name, surname, number, grades) { this.name = name; this.surname = surname; this.number = number; this.grades = grades; this.average = function() { return this.grades.reduce((a, c) => a + c, 0) / this.grades.length } } var student1 = new student("Peter", "Cat", 14444, [2, 3, 4]); console.log("Average: ", student1.average()) // add another grade: student1.grades.push(6) console.log("New Average: ", student1.average() )

We can use the Object Method to store the Average value:我们可以使用对象方法来存储平均值:

function Student(name, surname, number, grades = [])
{
    this.name = name;
    this.surname = surname;
    this.number = number;
    this.grades = grades;

    //Method to calculate the Average
    this.average = function()
    {
        if(this.grades.length !==0)
        {
            //Return the Average Calculation
            return this.grades.reduce((previous, current) => previous + current, 0) / this.grades.length
        }
        else
        {
            //This will return if grades not provided
            return "No Grades Mentioned"
        }
    }

}

//With Grades
var student1 = new Student("Srinivasan", "Raja", 1635, [22,43,67,89,90]);
console.log(student1, "Average: "+ student1.average());

//Without Grades
var student1 = new Student("Denny", "Lawrence", 1635);
console.log(student1, "Average: "+ student1.average());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM