使用OR运算符检查变量值 [英] checking a variable value using an OR operator
问题描述
所以,我团队的一名初级程序员今天编写了以下代码:
So, a junior programmer on my team today wrote the following piece of code:
if(status === ("incomplete" || "unknown"))
这显然不会按照他的意图行事,这是:
Which is obviously not going to do what he intended, which was this:
if(status === "incomplete" || status === "unknown"))
但我无法解释的是为什么第一段代码无法正常工作!或者,如果'status'设置为'incomplete',则为什么评估为true;如果设置为'unknown',则为false; ...
But what I can't explain is why exactly the first snippet of code wouldn't work! Or why it evaluates to true if 'status' is set to 'incomplete' but to false when it's set to 'unknown'...
推荐答案
在JavaScript中, ||
运算符返回其第一个操作数,如果它的计算结果为 true
(即它是不是 false
, null
, undefined
,,或
0
),否则为第二个操作数。
In JavaScript, the ||
operator returns its first operand if it evaluates to true
(i.e. it is not false
, null
, undefined
, ""
, or 0
), and its second operand otherwise.
在第一种情况下,(不完整||未知)
始终评估为不完整
,因为它评估为真。
In the first case, ("incomplete" || "unknown")
always evaluates to "incomplete"
, since it evaluates to true.
然后整个条件变为:
if (status === "incomplete")
这解释了您观察到的行为。
Which explains the behaviour you are observing.
这篇关于使用OR运算符检查变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!