为什么{} ==虚假评估,同时[] ==假的假的计算结果为真? [英] Why does {} == false evaluate to false while [] == false evaluates to true?
问题描述
为什么 {} ==虚假
评估为假
,而 [] ==假
计算结果为真正
在JavaScript?
Why does {} == false
evaluate to false
while [] == false
evaluates to true
in javascript?
推荐答案
这是类型转换,根据的摘要相等比较算法:
This is the type conversion that takes place according to the Abstract Equality Comparison Algorithm:
{} == 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
也正因为如此,preFER使用严格的比较。
And because of this, prefer to use strict comparison.
一些例子如何 ToPrimitive
将对象转换为基元比较期间的 的。默认情况下,该对象的的valueOf
方法将被调用,然后的toString
如果的valueOf
不返回原始值。对于日期
对象,它会调用的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
这篇关于为什么{} ==虚假评估,同时[] ==假的假的计算结果为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!