问题描述
var choice1 = prompt("Enter choice 1");
var choice2 = prompt("Enter choice 2");
if (choice1 === "x" && choice2 === ("a" || "b" || "c")) {
alert("Good job!");
}
假设用户为choice1
输入x
,为选择2输入c
.
Assume the user input x
for choice1
and c
for choice 2.
以上是一个简单的例子来突出我的问题.我知道这行不通,但是我的问题是为什么? Javascript不会将()
中的多个||
语句与choice2
进行比较.为什么不?我认为逻辑choice2
与"a"
或"b"
或"c"
是相同的类型和值(===
).
The above is a simple example to highlight my issue. I know it doesn't work but my question is why? Javascript won't compare the multiple ||
statements within ()
against choice2
. Why not? The logic in my mind is choice2
is the same type and value (===
) as "a"
or "b"
or "c"
.
我的工作方式是这样的:
The way I got it working was this:
(choice1 === "x" && ((choice2 === "a") || (choice2 === "b") || (choice3 === "c"));
请帮助我理解为什么使用多个||
时,您需要显式地写出每个||
方案,而不是像我尝试的那样在()
中放入一堆.谢谢.
Please help me understand why when using multiple ||
's, you need to explicitly write out each ||
scenario as opposed to putting a bunch within ()
as I tried up top. Thanks.
推荐答案
这种方式无法正常工作,您不能使用OR将一个值与多个其他值进行比较,而必须分别比较每个值.
It just doesn't work that way, you can't compare one value against multiple other values using OR, you have to compare each value individually.
您将获得的最接近的结果是使用Array.indexOf
The closest you'll get is using Array.indexOf
if ( ['a', 'b', 'c'].indexOf(choice2) != -1 )
它不起作用的原因是因为OR和AND检查一个真实值,所以在
The reason it doesn't work is because OR and AND checks for a truthy value, so in
('a' || 'b' || 'c') // return "a"
a
是真实值,因此OR永远不会进行,也不必这样做,它已经具有真实值,因此表达式为true,剩下的是a
,其余的将被丢弃
a
is a truthy value, so the OR never proceeds, it doesn't have to, it already has a truthy value so the expression is true, and you're left with a
, the rest is discarded
这篇关于Javascript逻辑运算符:多个||语法困境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!