问题描述
当操作数属于不同类型时,JavaScript关系比较运算符适用哪些规则?
What rules apply for the JavaScript relational comparison operators when the operands are of different types?
例如,如何> null
评估?我可以在我的开发者控制台中键入它,它会给出结果 true
,但是为什么?
For example, how is true > null
evaluated? I can type this into my developer console and it gives the result true
, but why?
我搜索了一个有点,但没有发现任何博客文章解释这个,虽然有很多解释类型强制==和===比较运算符。
I searched for a bit, but didn't find any blog posts explaining this, although there are plenty explaining type coercion for == and === comparison operators.
推荐答案
JavaScript关系运算符类型强制在中定义,具体在描述了运算符,以及和描述了强制操作数的过程。
JavaScript relational comparison operator type coercion is defined in the JavaScript specification, specifically in sections 11.8 to 11.8.5 which describe the operators, and sections 9.1 (ToPrimitive) and 9.3 (ToNumber) which describe the process of coercing the operands.
简而言之,4个比较运算符(<
,>
,< =
,> =
)尽力将每个操作数转换为数字,然后比较数字。例外情况是两个操作数都是字符串,在这种情况下它们按字母顺序进行比较。
In short, the 4 comparison operators (<
, >
, <=
, and >=
) do their best to convert each operand to a number, then compare the numbers. The exception is when both operands are strings, in which case they are compared alphabetically.
具体来说,
-
如果参数
o
是一个对象而不是一个原语,进行比较。例如,这意味着a< b
和a< aa
都返回true。If both arguments are Strings, compare them according to their lexicographical ordering. For example, this means
"a" < "b"
and"a" < "aa"
both return true.否则,,这意味着:
-
undefined
- >NaN
-
空
- > +0 -
布尔值
基元类型 - >1
如果true
,+0
如果false
-
字符串
- > 尝试从字符串 / li>
undefined
->NaN
Null
-> +0Boolean
primitive type ->1
iftrue
,+0
iffalse
String
-> try to parse a number from the string
然后按照您对运营商的预期比较每个项目,并注意任何涉及 NaN 评估为
false
。Then compare each item as you'd expect for the operator, with the caveat that any comparison involving
NaN
evaluates tofalse
.所以,这意味着以下内容:
So, this means the following:
console.log(true > null); //prints true console.log(true > false); //prints true console.log("1000.0" > 999); //prints true console.log(" 1000\t\n" < 1001); //prints true var oVal1 = { valueOf: function() { return 1; } }; var oVal0 = { toString: function() { return "0"; } }; console.log(oVal1 > null); //prints true console.log(oVal0 < true); //prints true console.log(oVal0 < oVal1); //prints true
这篇关于JavaScript关系比较运算符如何强制类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
-