我有一个while循环无法正常工作,无法找到问题。例如,我可以输入“ L”,它不会启动循环。有人看到我的问题吗?
<script>
var wood = prompt("Enter wood type (M)ahogany, (O)ak, (P)ine");
while (wood != "M" && wood != "m" && wood != "O" && wood != "o" && wood != "P" && wood != "p" && wood == "")
{
wood = prompt("invalid wood please enter (M)ahogany, (O)ak, (P)ine ");
}
</script>
答案 0 :(得分:3)
如上面的回答所述,您需要将空字符串更改为“ OR”而不是“ AND”
但是,我可能会像这样写一些可读性
let woods = ['M','O','P'];
while (!wood || !woods.includes(wood.toUpperCase()))
这样,您就不需要链接许多不同的变体。只需将其放入数组一次,然后将输入中的任何内容都转换为大写。
希望这会有所帮助。
答案 1 :(得分:1)
&& wood == ""
...仅在wood
为空的情况下为真,因此在您的条件中传递的唯一值是空字符串。
您可以将其更改为
while ((wood != "M" && wood != "m" && wood != "O" && wood != "o" && wood != "P" && wood != "p") || (wood == "")) { ...
或通过使用String.includes
var woods = "MOP";
var wood = prompt("Enter wood type (M)ahogany, (O)ak, (P)ine");
while (!( wood && woods.includes(wood.toUpperCase()) )) {
wood = prompt("invalid wood please enter (M)ahogany, (O)ak, (P)ine ");
}