[英]Why does “” < {} evaluate to true?
In JavaScript, why does: 在JavaScript中,为什么:
"" < {}
evaluate to true
and "" < {}
评估为true
和
"" < []
evaluate to false
? "" < []
评价为false
?
Because <
coerces its arguments. 因为
<
强迫其论点。 It prefers to compare numbers, but if the objects don't support a numeric primitive value, it does strings and you end up doing a lexical comparison. 它更喜欢比较数字,但如果对象不支持数字原始值,它会执行字符串,最后会进行词法比较。
String({})
is "[object Object]"
, but String([])
is ""
. String({})
是"[object Object]"
,但String([])
是""
。 "" < "[object Object]"
is true
, but "" < ""
is false
. "" < "[object Object]"
为true
,但"" < ""
为false
。
All the gory details are in the spec (fair warning, the language is turgid to put it mildly). 所有血淋淋的细节都在规范中 (公平警告,语言很温和)。
From your comment: 来自你的评论:
If it tries numbers first, consider that
Number({})
isNaN
andNumber([])
is0
.如果它首先尝试数字,则认为
Number({})
是NaN
而Number([])
是0
。 ComparingNaN < 0
evaluates tofalse
, and so does0 < NaN
.比较
NaN < 0
评估为false
,0 < NaN
也是如此。 Why are these results ignored?为什么忽略这些结果?
I put that poorly originally when I said originally that "...it tries numbers first..." (I've updated that). 当我最初说“......它首先尝试数字......”时 (我已经更新了),我最初说得很糟糕。 It doesn't.
它没有。 It just prefers numbers.
它只是喜欢数字。 Again, full details in soporific detail in the spec (various links from the above), but basically:
再次,详细说明中的详细信息(来自上面的各种链接),但基本上:
<
operation does the abtract ToPrimitive
operation on its operands. <
operation对其操作数执行abtract ToPrimitive
操作。 [[DefaultValue]]
method with the "hint" "Number". [[DefaultValue]]
方法。 [[DefaultValue]]
(hint = Number) invokes the valueOf
method of the objects and, if that method returns a primitive, returns it; [[DefaultValue]]
(hint = Number)调用对象的valueOf
方法,如果该方法返回一个原语,则返回它; if the result wasn't a primitive, [[DefaultValue]]
returns the result of toString
instead. [[DefaultValue]]
返回toString
的结果。 The valueOf
method of objects (including arrays) returns the original object unchanged, so the result is [[DefaultValue]]
returning the result of toString
. valueOf
方法返回原始对象不变,因此结果是[[DefaultValue]]
返回toString
的结果。 <
operation sees that the operands are both strings and compares them lexically. <
operation看到操作数都是字符串并且在词法上对它们进行比较。 Whereas if the operands were primitive numbers, ToPrimitive
would return the numbers unchanged, and the <
would compare them mathematically; 如果操作数是原始数字,
ToPrimitive
将返回数字不变,而<
将在数学上对它们进行比较; if they were Number
instances (remember JavaScript has both primitive and object versions of numbers, strings, and booleans), Number#valueOf
would be called by [[DefaultValue]]
, and Number#valueOf
returns the primitive number value. 如果它们是
Number
实例(记住JavaScript具有数字,字符串和布尔值的原始和对象版本),则Number#valueOf
将由[[DefaultValue]]
调用,而Number#valueOf
返回原始数字值。 And so <
would compare them mathmatically. 所以
<
会比较它们的数学。
Fun, eh? 好玩,嗯?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.