Javascript返回OR(||)操作的字符串 [英] Javascript returns string for OR(||) operation
问题描述
我无法理解这一点。
以下表达式使用OR运算符
Following is expression uses OR operator
var subCond1 = adj.getData('relationEnabled') == 'true' || adj.getData('unhideIfHidden') || adj.getData('hlFixed') == 'true';
我期待由于它是OR运算,它应该返回布尔值true / false,而是我结果得到字符串'false'。
I am expecting that since it is OR operation, it should return boolean true/false, but instead I get string 'false' as a result.
有人可以解释这个吗?
推荐答案
是的,这只是JavaScript中 ||
的功能之一,而且是故意的。它不返回一个布尔值(必然),它的工作方式如下:它评估左手操作数,如果该操作数是 truthy ,则返回它;否则,它会评估并返回右侧操作数。
Yup, that's just one of the features of ||
in JavaScript, and it's deliberate. It doesn't return a boolean (necessarily), it works like this: It evaluates the left-hand operand and if that operand is truthy, it returns it; otherwise, it evalutes and returns the right-hand operand.
那么什么是真实的?任何不虚假的东西。 :-)虚假值 0
,,
null
, undefined
, NaN
,当然还有 false
。其他任何事都是真的。
So what's "truthy"? Anything that isn't "falsy". :-) The falsy values are 0
, ""
, null
, undefined
, NaN
, and of course, false
. Anything else is truthy.
如果你需要一个布尔值,只需 !!
结果:
If you need a boolean, just !!
the result:
var subCond1 = !!(adj.getData('relationEnabled') == 'true' || adj.getData('unhideIfHidden') || adj.getData('hlFixed') == 'true');
...但你经常不需要打扰。
...but you frequently don't need to bother.
||
的这种行为非常有用,特别是(我发现)处理可能 null <的对象引用时/ code>,当你想提供一个默认值时:
This behavior of ||
is really useful, particularly (I find) when dealing with object references that may be null
, when you want to provide a default:
var obj = thisMayBeNull || {};
现在, obj
将 thisMayBeNull
如果它是真实的(非 - null
对象引用是真实的),或 {}
如果 thisMayBeNull
是假的。
Now, obj
will be thisMayBeNull
if it's truthy (non-null
object references are truthy), or {}
if thisMayBeNull
is falsy.
在我的博客上的这篇文章中有更多内容: JavaScript奇怪的强大OR运算符( ||
)
More in this article on my blog: JavaScript's Curiously-Powerful OR Operator (||
)
只是为了解决问题:&&
运算符具有类似的行为:它评估左侧操作数,如果它是 falsy ,则返回它;否则它会评估并返回右手操作员。如果你想要一个变量的对象属性,这可能是 null
:
Just to round things out: The &&
operator has a similar behavior: It evaluates the left-hand operand and, if it's falsy, returns it; otherwise it evaluates and returns the right-hand operator. This is useful if you want an object property from a variable which may be null
:
var value = obj && obj.property;
value
将是<$的值c $ c> obj 如果 obj
是 falsy (例如, null $
obj.property
,如果 obj
是真实的。
value
will be the value of obj
if obj
is falsy (for instance, null
), or the value of obj.property
if obj
is truthy.
这篇关于Javascript返回OR(||)操作的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!