我的while循环接受不应该的答案。为什么?

时间:2019-11-14 21:30:45

标签: javascript loops

我有一个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>

2 个答案:

答案 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 ");
}