【发布时间】:2016-08-29 19:42:37
【问题描述】:
我有一个食物总数的 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 块食物,因此它可能会反复从每种食物中去除 1 块,然后再回到饼干上。这是伯爵应该做的事情
下面的代码可以工作,但在循环时会卡住(超过 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)
}
}
【问题讨论】:
-
为什么用了两次星期五?
-
抱歉,错误 - 已删除。
-
不要修改代码。它使现有答案无效。
-
代码不是应该的样子
-
jsfiddle 请。否则,问题可能出在哪里还不是很清楚。例如。从上面的代码看来,
this.drinksData甚至不存在。
标签: javascript loops iteration nested-loops