汉堡包辅以一种或多种馅料
(不少于一种)。
但是,当我使用 ...stuffing
结果是 undefined
。
帮助我如何纠正这个任务,以便它计算所有成分的成本。
function Hamburger(size, ...stuffing) {
this.size = size;
this.stuffing = stuffing;
this.topping = [];
}
Hamburger.small = {
name: 'small',
price: 10,
kcal: 200
}
Hamburger.cheese = {
name: 'cheese',
price: 4,
kcal: 10
}
Hamburger.meet = {
name: 'meet',
price: 40,
kcal: 103
}
Hamburger.prototype.calculatePrice = () => {
let allCost = humb1.size.price + humb1.stuffing.price;
return `Total burger price: ${allCost}`
}
let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());
最佳答案
- 您不能按照您使用的方式使用箭头函数,您需要使用旧的
function
声明(或也使用 es6class
syntropic-sugar)。看看this answer了解原因(在您的情况下,您获得的是全局window
对象,而不是获取Hamburger
对象)。 - 请勿在
calculatePrice
的实现上使用humb1
,该函数是类原型(prototype)的一部分,而humb1
是一个类实例。 stuffing
是一个数组。您需要对每个项目进行操作才能获得总成本。我用过reduce
这里。
function Hamburger(size, ...stuffing) {
this.size = size;
this.stuffing = stuffing;
this.topping = [];
}
Hamburger.small = {
name: 'small',
price: 10,
kcal: 200
}
Hamburger.cheese = {
name: 'cheese',
price: 4,
kcal: 10
}
Hamburger.meet = {
name: 'meet',
price: 40,
kcal: 103
}
Hamburger.prototype.calculatePrice = function() {
let totalCost = this.size.price + this.stuffing.reduce((a, c) => a + c.price, 0);
return `Total burger price: ${totalCost}`;
}
let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.calculatePrice());
关于javascript - 通过特定属性计算对象数组的总和返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52579311/