为什么 {} == false 评估为 false 而 [] == false 评估为 true?
为什么 {} == false
评估为 false
而 [] == false
评估为 true
在 JavaScript 中?
Why does {} == false
evaluate to false
while [] == false
evaluates to true
in javascript?
推荐答案
这是根据抽象等式比较算法:
{} == false // step 7 {} == ToNumber(false)
{} == 0 // step 9 ToPrimitve({}) == 0
"[object Object]" == 0 // step 5 ToNumber("[object Object]") == 0
NaN == 0 // step 1.c.i
[] == false // step 7 [] == ToNumber(false)
[] == 0 // step 9 ToPrimitve([]) == 0
"" == 0 // step 5 ToNumber("") == 0
0 == 0 // step 1.c.iii
参考:ToNumber,ToPrimitive
因此,更喜欢使用严格比较.
And because of this, prefer to use strict comparison.
ToPrimitive
如何在比较过程中将对象转换为基元 的一些示例.默认情况下,将调用对象的 valueOf
方法,如果 valueOf
没有返回原始值,则调用 toString
.对于 Date
对象,它会默认调用 toString
.
Some examples how ToPrimitive
converts objects to primitives during comparison. By default, the valueOf
method of the object will be called, and then toString
if valueOf
doesn't return a primitive value. For Date
objects it will call toString
by default.
var obj = {};
obj.valueOf(); // Object { } // the object itself
obj.toString(); // "[object Object]"
obj.valueOf = function() { return 123; };
obj == 123; // true
obj.toString = function() { return 'foo bar'; };
obj == 123; // false
obj == 'foo bar'; // true
// Date object
var date = new Date();
date.valueOf(); // 1421430720379
date.toString(); // "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)"
date == 1421430720379 // false
date == "Fri Jan 16 2015 09:52:00 GMT-0800 (PST)" // true
date.toString = function() { return 'foo'; };
date == 'foo'; // true
相关文章