【发布时间】:2020-04-13 19:14:20
【问题描述】:
我正在尝试解决一个简单的咖啡店难题, 目标是检查该项目是否在菜单中,以及每次喝完后我是否有足够的豆子。
我试图 console.log 每一行 - 但我仍然不明白为什么它没有按预期运行 - 不知何故它进入一个 if 条件 - 然后也进入 else .. 我做错了什么?
感谢您的宝贵时间
`const coffeeShop = {
beans: 40,
drinkRequirements: {
latte: 10,
americano: 5,
doubleShot: 15,
frenchPress: 12
},
makeDrink: function (drinkType) {
const drinks = Object.keys(coffeeShop.drinkRequirements);
let drinkCost = coffeeShop.drinkRequirements[drinkType];
let binz = this.beans;
for (const key of drinks) {
if (key === drinkType){
if (drinkCost <= binz){
coffeeShop.beans = [binz - drinkCost]
console.log(`Good news! we have ${drinkType} and we have enough beans')
}
else {
console.log("OUT of beans!")
}
} else {
console.log(`we dont serve ${drinkType}`)
}
}
}
}
// tests that wont run correctly:
coffeeShop.makeDrink("latte");
coffeeShop.makeDrink("americano");
coffeeShop.makeDrink("filtered");
coffeeShop.makeDrink("doubleShot");
coffeeShop.makeDrink("frenchPress"); `
`see the console output I'm getting- its going the items again and again...`
`Good news! we have latte and we have enough beans
3main.js:328 Sooory Miss Sara- we dont serve latte
main.js:328 Sooory Miss Sara- we dont serve americano
main.js:322 Good news! we have americano and we have enough beans
2main.js:328 Sooory Miss Sara- we dont serve americano
4main.js:328 Sooory Miss Sara- we dont serve filtered
2main.js:328 Sooory Miss Sara- we dont serve doubleShot
main.js:322 Good news! we have doubleShot and we have enough beans
main.js:328 Sooory Miss Sara- we dont serve doubleShot
3main.js:328 Sooory Miss Sara- we dont serve frenchPress
main.js:325 Sorry Mam- we have frenchPress in the Menu - but we are OUT of
beans!`
【问题讨论】:
标签: javascript for-loop if-statement