将String中的String与null值进行比较

时间:2014-03-25 16:53:55

标签: javascript

我将值null与字符串进行比较。但是,比较结果始终为false

null > "a" // false

null < "a" // false

"a" > null // false

"a" > null // false

任何人都可以解释为什么会这样吗?

我确实在ECMAScript标准中找到了一个部分(http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5),似乎可以解释发生了什么,但我并不真正理解标准所说的内容。

2 个答案:

答案 0 :(得分:2)

11.8.5是抽象的关系表达式,production relational expression是您需要查看的内容,其中包括抽象的表达式。

11.8.1 The Less-than Operator ( < ) // pretty much the same as >

The production RelationalExpression : RelationalExpression < ShiftExpression is evaluated as follows:

    1) Let lref be the result of evaluating RelationalExpression.
    2) Let lval be GetValue(lref).
    3) Let rref be the result of evaluating ShiftExpression.
    4) Let rval be GetValue(rref).
--> 5) Let r be the result of performing abstract relational comparison 
       lval < rval. (see 11.8.5)
--> 6) If r is undefined, return false. Otherwise, return r.

当您查看抽象关系比较时,结果将是未定义,因为Number('a') =&gt; NaN(规则3)将引发这些规则:如果nx是NaN,则返回undefined 如果ny是NaN,则返回undefined

所以6)设r是执行抽象关系比较的结果,在你的情况下r是未定义的。最后一步是如果r未定义,则返回false ,因此您的回答。

答案 1 :(得分:0)

如果没有其他条件,则引用的第3节和第4节都说“返回错误”。

根据您引用的规范,没有任何其他选项。

并不是说它要么大于或小于任何意义。