我有食物总计的JS对象
foodData: [
{ biscuits: 2, cola:2, sandwiches:0, cake:0 },
{ biscuits: 2, cola:2, sandwiches:0, cake:0 },
{ biscuits: 2, cola:0, sandwiches:0, cake:0 },
{biscuits: 2, cola:0, sandwiches:0, cake:0 },
{biscuits: 2, cola:0, sandwiches:0, cake:0 },
{biscuits: 2, cola:0, sandwiches:4, cake:0 },
{biscuits: 0, cola:0, sandwiches:0, cake:4 }
],
我要做的是删除每天用户承诺的“糟糕食物”的数量。最终计算保存的卡路里。
应该从第一个索引中删除这些项目,然后按顺序删除,所以如果他们需要删除2位食物,如果可能的话会删除饼干,然后是可乐,然后是三明治,然后是蛋糕。
他们可以去掉5位食物,这样可以在每种食物中取一次,然后再回到饼干中。这就是伯爵应该做的事情
下面的代码可以工作,但在循环时会遇到困难(任何超过3项)。我怀疑它是if语句或可能是内部计数。关于如何停止陷入持续循环的任何建议。我认为在满足条件时突破if语句会有所帮助。
var array_of_functions = [this.totalMonday, this.totalTuesday, this.totalWednesday, this.totalThursday, this.totalThursday, this.totalFriday, this.totalSaturday, this.totalSunday];
for (i = 0; i < array_of_functions.length; i++) {
if (array_of_functions[i] > 0) {
count = 0;
do {
if (this.foodData[i]['biscuits'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['biscuits']--;
++count;
}
if (this.foodData[i]['cola'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['cola']--;
++count;
}
if (this.drinksData[i]['sandwiches'] > 0 && count < this.noRemovedFoods) {
this.drinksData[i]['sandwiches']--;
++count;
}
if (this.foodData[i]['cake'] > 0 && count < this.noRemovedFoods) {
this.dataData[i]['cake']--;
++count;
}
} while (count < this.noRemovedFoods)
}
}
答案 0 :(得分:0)
如果您提供了更多代码或具有适当有意义的代码(例如我不知道drinkData是什么),那将是一件好事。我假设你的代码在do-while循环中看起来像这样:
if (this.foodData[i]['biscuits'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['biscuits']--;
++count;
}
if (this.foodData[i]['cola'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['cola']--;
++count;
}
if (this.foodData[i]['sandwiches'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['sandwiches']--;
++count;
}
if (this.foodData[i]['cake'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['cake']--;
++count;
}
在这种情况下,你将陷入无限循环。问题出在你的do-while循环条件中。如果所有foodData项位都变为零,并且由于不满足条件count < this.noRemovedFoods
而陷入无限循环,则会出现计数不会增加的情况。
如果所有食品位都变为零,你可以做的一件事是打破do-while循环。如果我按照我的理解考虑你的代码,重写上面的代码以打破do-while循环可能如下所示:
do {
if (this.foodData[i]['biscuits'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['biscuits']--;
++count;
}
if (this.foodData[i]['cola'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['cola']--;
++count;
}
if (this.foodData[i]['sandwiches'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['sandwiches']--;
++count;
}
if (this.foodData[i]['cake'] > 0 && count < this.noRemovedFoods) {
this.foodData[i]['cake']--;
++count;
}
if(this.foodData[i]['biscuits'] == 0 && this.foodData[i]['cola'] == 0 && this.foodData[i]['sandwiches'] == 0 && this.foodData[i]['cake'] == 0) {
break;
}
}
检查所有食物项目是否已变为零以突破执行循环。