简体   繁体   中英

Obj.toString() both equal to false and true?

In a blank page on chrome console I type:

var o={};
o.toString() == false // false
o.toString() == true // false

I'm expecting o.toString to be evaluated as an empty string and so falsy...

What is happening?

Because {}.tostring() produces "[object Object]"

Your empty string assumption was incorrect and easily tested in a console

I'm expecting o.toString to be evaluated as an empty string and so falsy...

That expectation is at odds with the specified behavior of Object.prototype.toString (which is what ({}).toString is), which is to output "[object Object]" for plain objects.

So what you're doing is

"[object Object]" == true

(or == false ). If we follow the (convoluted) rules of the abstract equality comparison algorithm , that ends up being

Number("[object Object]") === Number(true)

...which is

NaN === 1

...which is false , because NaN isn't equal to anything.

Similarly

"[object Object]" == false

...ends up being

NaN === 0

...which is also false , because (again) NaN isn't equal to anything.

In a comment you've asked:

So why not truthy?

There's a big difference between coercing a value to boolean, like this:

if (o.toString()) {

...and comparing it to a boolean via == , like this:

if (o.toString() == true) {

They're just defined fundamentally differently, because == goes through a defined series of steps to try to make the values things it can compare, and it doesn't bias toward booleans when doing that (it biases toward numbers and strings).

It's because o={} and function toString return you "[object Object]"

If you need to get true / false if object is empty use something like:

ES5

var o1 = {};
if(Object.getOwnPropertyNames(o).length !== 0) console.log('true');
else console.log('false');

JQUERY: Check this: http://api.jquery.com/jQuery.isEmptyObject/

if($.isEmptyObject(o)) console.log('true');

Loadash :

if(_.isEmpty(o)) console.log('true');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM