[英]JavaScript: Return Rating Value from Array Using Internal Prototype Method within Factory Function
我試圖從工廠功能創建一個對象。 該對象包含一個內部原型,該原型由不同的方法組成。
我被困在從getStars()方法返回的內容上。
內部原型:
const obj = {
addStars(rating){
return this.rating.push(rating)
},
getStars(?){
???
}
}
工廠功能:
function createRecipe (ingredients, cooktime, rating='') {
let instance = Object.create(obj)
instance.ingredients = ingredients;
instance.cooktime = cooktime;
instance.rating = [];
return instance
}
正在創建的對象:
const recipe1 = createRecipe(['cheese', 'dough', 'basil'], 20)
現在,我可以將其他人的starRatings添加到對象屬性中的rating數組中。 如下所示:
recipe1.addStars('*****');
recipe1.addStars('***');
recipe1.addStars('*');
我的問題是,我希望內部原型中的getStars方法采用添加到“評分”數組中的所有星級的平均值。
我希望看到的是:
recipe1.getStars(); // returns 3
如何操縱getStars()方法以獲得所需的結果?
只需使用reduce
將所有值求和,然后除以長度即可。
getStars() {
let allStars = this.ratings.reduce((a, { length: c }) => a + c, 0);
let avg = allStars / this.ratings.length;
return avg;
}
或單線:
getStars() {
return this.ratings.reduce((a, { length: c }) => a + c, 0) / this.ratings.length;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.