请参阅下面粗体部分。如果有人能帮助我,我将不胜感激。 如何确保 addRating() 方法的输入介于 1 和 5 之间?也许有某种方法可以阻止代码继续/处理平均评分,如果其中一个评分低于 1 且高于 5。
class Media {
constructor(title) {
this._title = title;
this._isCheckedOut = false;
this._ratings = [];
}
get title() {
return this._title;
}
get isCheckedOut() {
return this._isCheckedOut;
}
get ratings() {
return this._ratings;
}
set isCheckedOut(status) {
this._isCheckedOut = status;
}
toggleCheckOutStatus() {
this.isCheckedOut = !this.isCheckedOut;
}
getAverageRating() {
let ratingsSum = this.ratings.reduce((accumulator, currentRating) =>
accumulator + currentRating);
return ratingsSum/this.ratings.length;
}
// Here is the mentioned function
// look inside addRating()
addRating(newRating) {
if (newRating < 1 || newRating > 5) {
console.log("Invalid Input. Please enter an integer between 1-
5.");
} else {
this.ratings.push(newRating);
}
}
}
class Book extends Media {
constructor(author, title, pages) {
super(title);
this._author = author;
this._pages = pages;
}
get author() {
return this._author;
}
get pages() {
return this._pages;
}
}
class Movie extends Media {
constructor(director, title, runTime) {
super(title);
this._director = director;
this._runTime = runTime;
}
get director() {
return this._director;
}
get runTime() {
return this._runTime;
}
}
const historyOfEverything = new Book('Bill Bryson', 'A Short History of Nearly Everything', 544);
historyOfEverything.toggleCheckOutStatus();
console.log(historyOfEverything.isCheckedOut);
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);
console.log(historyOfEverything.getAverageRating());
const speed = new Movie('Jan de Bont', 'Speed', 116);
speed.toggleCheckOutStatus();
console.log(speed.isCheckedOut);
speed.addRating(1);
speed.addRating(1);
speed.addRating(5);
console.log(speed.getAverageRating());
一只甜甜圈
慕容森
蝴蝶刀刀
相关分类