Home > Web Front-end > JS Tutorial > A simple way to determine whether an object {} is an empty object in JavaScript

A simple way to determine whether an object {} is an empty object in JavaScript

高洛峰
Release: 2017-01-04 09:53:30
Original
1734 people have browsed it

I encountered a problem when working on a project, to determine whether an object is an empty object. I found that it can be judged this way, and the code is:

1. Code 1:

var a = {};
if(!a){ console.log(1);}
else if(a == null) { console.log(2);}
else { console.log(3);}
Copy after login

The result is: 3

2. Code 2:

var b = {};
if(b == {}){ console.log(4);}
if(b == '{}') { console.log(5);}
if(typeof(b) == 'object') { console.log(6);}
Copy after login

The result is: 6

3. Code 3:

var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
Copy after login
Copy after login
var c = {};
if(JSON.stringify(c) == "{}"){ console.log(7);}
Copy after login
Copy after login

The result is: 7

So you can use the method of code 3 to determine whether the object is an empty object{};

If the object is not empty, and you know that when the object is not empty, a certain attribute (such as {id:111}) must exist, you can judge like this:

4. Code 4:

var d = {};
var e = {id:111};
if(d.id){ console.log(8);}
if(e.id){ console.log(9);}
Copy after login

The result is: 9

Summary: Obviously the judgment method of code 3 is relatively "strong", but the efficiency is obviously not as good as the judgment method of code 4

The above is the simple method of JavaScript to determine whether an object {} is an empty object brought by the editor. I hope everyone will support the PHP Chinese website~

More JavaScript to determine whether an object { }For related articles on the simple method of whether it is an empty object, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template