JavaScript 判断一个对象是否为空

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JavaScript 判断一个对象是否为空

水流云在   2020-03-08 我要评论
本文介绍了几种判断一个对象是否为空方法。如有错误或建议,烦请指正。 **测试用例** ```js test1 = 1; test2 = {}; test3 = {a:1,b:2} ``` ## 1. 判断 Object.keys() 的长度 ```js function _isNull(obj) { if(Object.prototype.toString.call(obj)!=='[object Object]') { return 'Type Error' } return Object.keys(obj).length === 0 } _isNull(test1); // "Type Error" _isNull(test2); // true _isNull(test3); // false ``` ## 2. for in 遍历对象的 keys ```js function _isNull(obj) { if(Object.prototype.toString.call(obj)!=='[object Object]') { return 'Type Error' } for(keys in obj) { return false } return true } _isNull(test1); // "Type Error" _isNull(test2); // true _isNull(test3); // false ``` ## 3. Object.getOwnPropertyNames() 获取对象的自有属性名,空对象没有自有属性 ```js function _isNull(obj) { if(Object.prototype.toString.call(obj)!=='[object Object]') { return 'Type Error' } return Object.getOwnPropertyNames(obj).length === 0 } _isNull(test1); // "Type Error" _isNull(test2); // true _isNull(test3); // false ``` ## 4. JSON.stringify() [JSON 对象介绍](https:/https://img.qb5200.com/download-x/developer.mozilla.org/zh-CNhttps://img.qb5200.com/download-x/docs/Web/JavaScript/Reference/Global_Objects/JSON) 先将对象转换成 JSON 字符串,然后比较 ```js function _isNull(obj) { if(Object.prototype.toString.call(obj)!=='[object Object]') { return 'Type Error' } return JSON.stringify(obj) === '{}' } _isNull(test1); // "Type Error" _isNull(test2); // true _isNull(test3); // false ```

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们