当包含减法条件时,我在 JavaScript 中的 while 循环陷入无限循环
我正在做这个练习,你必须计算获得果汁所需的酸橙数量。 它需要一个 switch 语句,其中取出“limes”数组的第一个元素(并且可以完美地工作)。直到我添加条件来倒数楔形:即使在这种情况下指定减去确定的数量,在每次迭代中它似乎都会忽略它并且永远不会满足中断 switch 语句所需的条件
代码
function limesToCut(wedgesNeeded, limes) {
let limesNeeded = 0
while(limes.length != 0 || wedgesNeeded > 0 ) {
switch (limes[0]) {
case 'small':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 6
break;
case 'medium':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 8
break;
case 'large':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 10
break;
default:
break
}
}
console.log(limesNeeded)
}
//test cases
console.log("case 1")
limesToCut(4, ['medium', 'small'])
console.log("case 2")
limesToCut(80,['small','large','large','medium','small','large','large',])
console.log("case 3")
limesToCut(0, ['small', 'large', 'medium'])
console.log("case 4")
limesToCut(10, [])
这是我去哪里的 错误的?即使我从循环中排除其他条件,它似乎也不起作用
I'm doing this exercise where you have to calculate the number of limes needed to get the juice.
It needs a switch statement inside which takes out the first element of the "limes" array, (and that works flawlessly). Until i add the condition to count down the wedges: even if in the cases is specified to subtract a determined amount, at every iteration it seems to ignore it and never meeting the needed condition to break the switch statement
here's the code
function limesToCut(wedgesNeeded, limes) {
let limesNeeded = 0
while(limes.length != 0 || wedgesNeeded > 0 ) {
switch (limes[0]) {
case 'small':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 6
break;
case 'medium':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 8
break;
case 'large':
limes.shift()
limesNeeded += 1
wedgesNeeded -= 10
break;
default:
break
}
}
console.log(limesNeeded)
}
//test cases
console.log("case 1")
limesToCut(4, ['medium', 'small'])
console.log("case 2")
limesToCut(80,['small','large','large','medium','small','large','large',])
console.log("case 3")
limesToCut(0, ['small', 'large', 'medium'])
console.log("case 4")
limesToCut(10, [])
where did i go wrong? it seems to not be working even when i exclude the other condition from the loop
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在评论中引用@James:
这是因为对于您的某些测试用例,
limes.length != 0 ||需要楔子> 0
始终为 true,因此会陷入循环。考虑一下这样的情况:您需要 80 个楔子,但只有 7 个酸橙,可以产生 70 个楔子顶部(如果它们都是最大尺寸)。所以没有剩下酸橙,只有楔子需要> 0,所以一直循环下去。quoting @James in the comments:
It's because for some of your test cases,
limes.length != 0 || wedgesNeeded > 0
is always true, so it gets stuck in a loop. Consider the case where you need 80 wedges but only have 7 limes which could yield 70 wedges tops (if they were all the largest size). So there are no limes left but wedgesNeeded > 0, so it loops and loops.