65 lines
1.5 KiB
JavaScript
65 lines
1.5 KiB
JavaScript
// 1
|
|
// 创建一个记录学生成绩的对象,提供一个添加成绩的方法,以及一个显示学生平均成绩的方法。
|
|
function createTranscript() {
|
|
this.gradeList = [];
|
|
this.add = (num) => {
|
|
this.gradeList.push(num);
|
|
};
|
|
this.calcAvge = () => {
|
|
const sum = this.gradeList.reduce((sum, grade) => {
|
|
sum += grade;
|
|
return sum;
|
|
}, 0);
|
|
return sum / this.gradeList.length;
|
|
};
|
|
}
|
|
|
|
const transcript1 = new createTranscript();
|
|
transcript1.add(120);
|
|
transcript1.add(80);
|
|
console.log(transcript1.calcAvge());
|
|
|
|
// 2
|
|
// 将一组单词存储在一个数组中,并按正序和倒序分别显示这些单词
|
|
const list = ["fan", "sheng", "fa", "lan", "xiu", "ping"];
|
|
for (let i = 0; i < list.length; i++) {
|
|
console.log(list[i]);
|
|
}
|
|
console.log("--------------------------")
|
|
for (let i = list.length - 1; i >= 0; i--) {
|
|
console.log(list[i]);
|
|
}
|
|
|
|
// 3
|
|
function weekTemps() {
|
|
this.dataStore = [];
|
|
for (let i = 0; i < 12; i++) {
|
|
this.dataStore.push([])
|
|
}
|
|
this.add = add;
|
|
this.average = average;
|
|
}
|
|
|
|
function add(month, temp) {
|
|
this.dataStore[month].push(temp);
|
|
}
|
|
|
|
function average() {
|
|
var total = 0;
|
|
for (var i = 0; i < this.dataStore.length; ++i) {
|
|
total += this.dataStore[i];
|
|
}
|
|
return total / this.dataStore.length;
|
|
}
|
|
|
|
var thisWeek = new weekTemps();
|
|
thisWeek.add(52);
|
|
thisWeek.add(55);
|
|
thisWeek.add(61);
|
|
thisWeek.add(65);
|
|
thisWeek.add(55);
|
|
thisWeek.add(50);
|
|
thisWeek.add(52);
|
|
thisWeek.add(49);
|
|
print(thisWeek.average()); // displays 54.875
|