Home > Article > Web Front-end > js method to determine whether object is empty
In php, empty arrays and empty objects are false when performing Boolean value verification, but arrays or objects in js are all true regardless of whether there are attributes or values.
This is very painful in the process of writing programs. In order to solve this problem, you can only write your own method to judge. Here is a summary of several methods
// 用es6的keys方法搞定function isEmpty(obj){ return Object.keys(obj).length === 0; }// 利用JSON转换搞定function isEmpty(obj){ return JSON.stringify(obj) == '{}'; }// 利用for in或for of等写个for in的例子function isEmpty(obj){ for(let item in obj){ return true; } return false; }
All of the above are acceptable, but the efficiency needs to be verified. Visually, the third method should be the fastest. Note that let is used in the third method. This is the usage of es6. If you want to be compatible with old IE, you still need to use var
The above is the detailed content of js method to determine whether object is empty. For more information, please follow other related articles on the PHP Chinese website!