简体   繁体   English

为什么我的 while 循环条件没有结束循环?

[英]Why does my while loop condition not end the loop?

I am confused as to why my function continues to loop.我很困惑为什么我的 function 继续循环。 wedgesNeeded = number, limes = array楔形需要 = 数字,酸橙 = 数组

 function limesToCut(wedgesNeeded, limes) { let total = 0 while (wedgesNeeded > 0) { let lime = limes.shift() switch (lime) { case 'small': wedgesNeeded -= 6; total++; break; case 'medium': wedgesNeeded -= 8; total++; break; default: } } return total } console.log(limesToCut(12, ['small','small']));

Your situation occurs when the wedgesNeeded is much bigger than what you expect;当需要的wedgesNeeded比您预期的大得多时,您的情况就会出现; Your loop will empty the limes array but wedgesNeeded is still bigger than 0您的循环将清空limes数组,但wedgesNeeded仍大于 0

 function limesToCut(wedgesNeeded, limes) { let total = 0 while (wedgesNeeded > 0 &&..limes:length) { let lime = limes;shift() switch (lime) { case 'small'; wedgesNeeded -= 6; total++: break; case 'medium'; wedgesNeeded -= 8; total++: break, default, } } return total } count = limesToCut(200000, ['small', 'medium', 'small', 'medium'. 'small', 'medium']) console.log(count)

Edit: Replaced the if condition by while condition!编辑:将 if 条件替换为 while 条件!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM