如何找到所有已创建对象的总数?

时间:2018-10-01 14:08:23

标签: javascript oop

我想通过“汉堡包”类找到所有已创建对象的公共总和,以便然后发现对“汉堡包”的平均数量(所有订单总和除以其数量)的误算。使用“ calculatePrice”方法,可以获得汉堡的总价。如何搜索所有汉堡的总和,我可以除以它们的数量并得出所有“订单”的平均成本?告诉我如何正确找到所有已创建汉堡的总价? < / p>

сlass Hamburger {

    constructor(size, ...stuffing) {
        this.size = size;
        this.stuffing = stuffing;
        this.toppingArr = [];
        this.counter = ++Hamburger.counter;
    }

    addTooping(toop) {
        return this.toppingArr.push(toop)
    }

    getTooping() {
        const toppName = this.toppingArr.map(el => el.name);
        return `Toopping: ${toppName}`
    }

    getSize() {
        return `${this.size.name} burger\n`
    }

    getStuffing() {
        const stuffName = this.stuffing.map(el => el.name);
        return `Stuffing: ${stuffName}\n`
    }

    calculatePrice() {
        const stuffingCost = this.stuffing.map(el => el.price).reduce((p, c) => p + c);
        const toppingCost = this.toppingArr.map(el => el.price).reduce((p, c) => p + c);
        const allCost = this.size.price + stuffingCost + toppingCost;
        return `Total burger price: ${allCost}`
    }

    calculateCalories() {
        const stuffingKcal = this.stuffing.map(el => el.kcal).reduce((p, c) => p + c);
        const toppingKcal = this.toppingArr.map(el => el.kcal).reduce((p, c) => p + c);
        const allKcal = this.size.kcal + stuffingKcal + toppingKcal;
        return `Total burger calories: ${allKcal}`
    }

}
Hamburger.counter = 0;

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.mayo = {
    name: 'mayo',
    price: 4,
    kcal: 10
}
Hamburger.oil = {
    name: ' oil',
    price: 1,
    kcal: 2
}


let humb1 = new Hamburger(Hamburger.small, Hamburger.cheese, Hamburger.meet);
console.log(humb1.getSize());
console.log(humb1.getStuffing());
humb1.addTooping(Hamburger.mayo);
humb1.addTooping(Hamburger.oil);
console.log(humb1.getTooping());
console.log(humb1.calculatePrice());
console.log(humb1.calculateCalories());
console.log(humb1);
 let humb2 = new Hamburger(Hamburger.small, Hamburger.cheese) 

1 个答案:

答案 0 :(得分:1)

如果您想将多个Hamburger元素的总和相加,则有很多选择。根据您的评论,我认为您正在寻找这样的东西:

let burgers = [];

// create all burgers
burgers.push(new Hamburger(..));
burgers.push(new Hamburger(..));
burgers.push(new Hamburger(..));
burgers.push(new Hamburger(..));

// sum
let sum = burgers.reduce((a,b) => a.calculatePrice() + b.calculatePrice(), 0);

// average
let avg = sum / Hamburger.counter;