gpt4 book ai didi

JavaScript:使用工厂函数中的内部原型(prototype)方法从数组返回评级值

转载 作者:行者123 更新时间:2023-12-02 23:23:56 26 4
gpt4 key购买 nike

我正在尝试从工厂函数创建一个对象。该对象包含一个由不同方法组成的内部原型(prototype)。

我不知道从 getStars() 方法返回什么。

内部原型(prototype):

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 添加到对象属性中的评级数组中。如下:

recipe1.addStars('*****');
recipe1.addStars('***');
recipe1.addStars('*');

我的问题是我希望内部原型(prototype)中的 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;
}

关于JavaScript:使用工厂函数中的内部原型(prototype)方法从数组返回评级值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56821845/

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