gpt4 book ai didi

javascript - 循环遍历对象数组并获取平均值

转载 作者:行者123 更新时间:2023-12-02 17:59:14 28 4
gpt4 key购买 nike

我希望循环遍历原型(prototype)函数中的对象数组。循环后,我想获取 gpa 数组的平均值,然后控制台记录名称、地址、gpa 和平均 gpa。除了平均水平以外,我都能做到。我希望这一切都在测试功能中一起运行。感谢您的所有帮助。

var students = [{
name: "Walker",
address: {
street: "123 South Drive",
city: 'Sarasota',
state: 'FL'
},
gpa: [3.0, 3.4, 3.8]
}, {
name: "Christian",
address: {
street: "5601 Pebble Beach Ln",
city: 'Sacromento',
state: 'CA'
},
gpa: [2.5, 3.6, 3.8]
}];

var stud = Students(students);



stud.testing();

构造函数:

var Students = function (students) {
return new Students.prototype.init(students);
}

Students.prototype = {
init: function (students) {
this.students = students;
},
testing: function () {


for (i = 0; i < this.students.length; i++) {
i = i % this.students.length;


for (j = 0; j < this.students.length; j++) {



this.gpa1 = this.students[j].gpa;
this.len = this.students[j].gpa.length;

//console.log(this.gpa1);

this.average = this.gpa1[0] + this.gpa1[1] + this.gpa1[2];
this.res = this.average / this.len;
console.log(this.res);
}




console.log("Name: " + this.students[i].name);
console.log("Address: " + this.students[i].address.street + ' ' + this.students[i].address.city + ' ' + this.students[i].address.state);
console.log("GPA: " + this.students[i].gpa);
console.log("Average: " + this.gpa1);


}
},
addData: function (student3) {
this.students.push(student3);
}

最佳答案

这应该很简单,循环遍历学生,然后循环遍历他们的 GPA 分数,将它们相加并除以总分:

testing: function () {
var total = 0;
var numPoints = 0;
for (var i = 0; i < this.students.length; i++) {
var thisStudentsTotal = 0;
for (var j = 0; j < this.students[i].gpa.length; j++) {
total += this.students[i].gpa[j];
thisStudentsTotal += this.students[i].gpa[j];
numPoints++;
}
// This is the average for just this student
this.students[i].myAvg = thisStudentsTotal / this.students[i].gpa.length;
}
// This is the average for every student
var theAverage = total / numPoints;
}

关于javascript - 循环遍历对象数组并获取平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20705481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com