Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

javascript - Why does {} == false evaluate to false while [] == false evaluates to true?

Why does {} == false evaluate to false while [] == false evaluates to true in javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

References: ToNumber, ToPrimitive

And because of this, prefer to use strict comparison.


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...