Home > Web Front-end > JS Tutorial > How to check if an object is empty in Javascript

How to check if an object is empty in Javascript

青灯夜游
Release: 2021-10-20 18:10:35
Original
19055 people have browsed it

Method: 1. Convert the object into a json string and determine whether the string is "{}"; 2. Use the "$.isEmptyObject(object)" statement; 3. Use "Object.getOwnPropertyNames( Object)" statement; 4. Use "Object.keys(Object)".

How to check if an object is empty in Javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Javascript checks whether the object is empty

1. Convert the json object into a json string, and then determine whether the string is "{ }"

var data = {};
var b = (JSON.stringify(data) == "{}");
alert(b);//true
Copy after login

2. jquery's isEmptyObject method

This method encapsulates the 2 methods (for in) by jquery. You need to rely on jquery

var data = {};
var b = $.isEmptyObject(data);
alert(b);//true
Copy after login
when using it.

3. Object.getOwnPropertyNames() method

This method uses the getOwnPropertyNames method of the Object object to obtain the property names in the object, store them in an array, and return the array object. We can judge the array by length to determine whether this object is empty

Note: This method is not compatible with ie8, and other browsers have not tested it

var data = {};
var arr = Object.getOwnPropertyNames(data);
alert(arr.length == 0);//true
Copy after login

4. Use the Object.keys() method of ES6

Similar to method 3, it is a new method of ES6. The return value is also an array composed of property names in the object

var data = {};
var arr = Object.keys(data);
alert(arr.length == 0);//true
Copy after login

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to check if an object is empty in Javascript. For more information, please follow other related articles on 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