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

How to determine whether an object is empty in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-12 10:35:3413191browse

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("对象不为空");
}

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("对象不为空");
    }

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!

Statement:
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