Home > Web Front-end > JS Tutorial > body text

js method to determine whether object is empty

一个新手
Release: 2017-10-02 09:43:40
Original
2561 people have browsed it

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;
}
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!