当操作数属于不同类型时,JavaScript 关系比较运算符适用哪些规则?
例如,true > null
是如何求值的?我可以将其输入到我的开发人员控制台,它会给出结果 true
,但为什么呢?
我搜索了一下,但没有找到任何解释这一点的博客文章,尽管有很多解释 == 和 === 比较运算符的类型强制转换。
最佳答案
JavaScript 关系比较运算符类型强制在 JavaScript specification 中定义,特别是在 11.8 to 11.8.5 部分描述运算符和部分 9.1 (ToPrimitive)和 9.3 (ToNumber)其中描述了强制操作数的过程。
简而言之,4 个比较运算符(<
、>
、<=
和 >=
)会尽力将每个操作数转换为数字,然后比较数字。异常(exception)情况是两个操作数都是字符串,在这种情况下它们按字母顺序进行比较。
具体而言,
如果参数
o
是一个对象而不是原始类型,try to convert it to a primitive value调用o.valueOf()
或者 - 如果o.valueOf
未定义或调用时未返回原始类型 - 通过调用o.toString()
如果两个参数都是字符串,则根据它们的 lexicographical ordering 比较它们.例如,这意味着
"a" < "b"
和"a" < "aa"
两者都返回 true。否则,convert each primitive to a number ,这意味着:
-
undefined
->NaN
-
Null
-> +0 -
Boolean
原始类型 ->1
如果true
,+0
如果false
-
String
-> try to parse a number来自字符串
-
然后按照您对运算符的预期比较每一项,但需要注意的是任何涉及
NaN
的比较评估为false
.
所以,这意味着:
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 - JavaScript 关系比较运算符如何强制类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14687876/