Home > Web Front-end > JS Tutorial > How to determine whether an object is empty in javascript

How to determine whether an object is empty in javascript

醉折花枝作酒筹
Release: 2022-10-14 16:25:27
Original
13230 people have browsed it

Method: 1. Use the "JSON.stringify()" method to convert the object into a json string, and then determine whether the string is "{}"; 2. Use "Object.keys(object name) ).length==0" determines whether the length is 0, and then determines whether the object is empty.

How to determine whether an object is empty in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

1. Determine through the JSON.stringify() method

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

var obj = {};
var objStr = JSON.stringify(obj);
if(objStr === '{}') {
  console.log("对象为空");
}else {
  console.log("对象不为空");
}
Copy after login

Note: Why toString() is not used here is because it returns Object.

2. Use the es6 method Object.keys() length property for judgment

var obj = {};
var arr = Object.keys(obj);
if (arr.length == 0){
   console.log("对象为空");
}else {   
   console.log("对象不为空");
    }
Copy after login

Object.keys method is used for traversal in JavaScript A method of an object's properties. The parameter it passes in is an object, and what it returns is an array. The array contains all the property names of the object.

You can use the length attribute to determine whether this array is empty, and then determine whether the object is empty.

[Recommended learning: javascript video tutorial]

The above is the detailed content of How to determine whether 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