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
70 views
in Technique[技术] by (71.8m points)

javascript - How to check whether an object is empty?

I'm learing JavaScript. I cannot grasp the idea of an empty object. As I understand, there are situations when I need to check a variable whether it holds an object and has a value.

So far, I know that a variable can be undefined.

var car; // the value is undefined, as well as the type (which is it? number, array, etc.)

I also know, that everything that has a value, is true:

var car = "Opel";
Boolean(car); // true 

And anything without a value is false:

var car = ""; // typeof string, but it is empty, so
Boolean(car); // false
Boolean(null); // false 

So why doesn't it work the same way with arrays and objects? Why is all of this true? Shouldn't empty arrays and objects return false?

var car = {make: "Opel", year: 2015};
Boolean(car); // true
car = {};
Boolean(car); // true
car = ["BMW", "Opel"]; 
Boolean(car); // true
car = [];
Boolean(car); // true

Now I see that there are methods, that can be applied to check an object's length, I just haven't reached that part yet.

I'm learning at W3Schools website and this bit just got me puzzled:

But you cannot test if an object is null, because this will throw an error if the object is undefined:

Incorrect:

if (myObj === null) 

To solve this problem, you must test if an object is not null, and not undefined.

But this can still throw an error:

Incorrect:

if (myObj !== null && typeof myObj !== "undefined")

Because of this, you must test for not undefined before you can test for not null:

Correct:

if (typeof myObj !== "undefined" && myObj !== null)

I still cannot understand the last line here.

question from:https://stackoverflow.com/questions/65926112/how-to-check-whether-an-object-is-empty

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

1 Answer

0 votes
by (71.8m points)

Checking if an object is empty:

Object.keys(yourObject).length

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

...