Get the App
SLTechnology News&Howtos  ›  Development  › 

How to check whether an object is empty with Javascript

Shulou Source: shulou.com Published: 2022-06-03 02:47:44 09月18日 Update

This article mainly explains "how to use Javascript to check whether the object is empty". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use Javascript to check whether the object is empty".

Methods: 1, convert the object into a json string to determine whether the string is "{}"; 2, use the "$.isEmptyObject" statement; 3, use the "Object.getOwnPropertyNames" statement; 4, use "Object.keys".

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, 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

2. IsEmptyObject method of jquery

This method is encapsulated by jquery method 2 (for in), and it depends on jquery when using it.

Var data = {}; var b = $.isEmptyObject (data); alert (b); / / true

3. Object.getOwnPropertyNames () method

This method uses the getOwnPropertyNames method of the Object object to get the property name in the object, save it in an array, and return the array object. We can judge whether the object is empty by judging the length of the array.

Note: this method is not compatible with ie8. Other browsers have not tested it.

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

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

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

Var data = {}; var arr = Object.keys (data); alert (arr.length = = 0); / / true thank you for reading, the above is "how to use Javascript to check whether the object is empty", after the study of this article, I believe you have a deeper understanding of how to use Javascript to check whether the object is empty, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Objects methods checks characters strings arrays this method learning content properties statements can be passed that is ideas situations tutorials articles more browsers environments Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Tech Info NVidia Linux OPPO Reno