栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

对象是空的吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

对象是空的吗?

我假设用 表示“没有任何属性”。

// Speed up calls to hasOwnPropertyvar hasOwnProperty = Object.prototype.hasOwnProperty;function isEmpty(obj) {    // null and undefined are "empty"    if (obj == null) return true;    // Assume if it has a length property with a non-zero value    // that that property is correct.    if (obj.length > 0)    return false;    if (obj.length === 0)  return true;    // If it isn't an object at this point    // it is empty, but it can't be anything *but* empty    // Is it empty?  Depends on your application.    if (typeof obj !== "object") return true;    // Otherwise, does it have any properties of its own?    // Note that this doesn't handle    // toString and valueOf enumeration bugs in IE < 9    for (var key in obj) {        if (hasOwnProperty.call(obj, key)) return false;    }    return true;}

例子:

isEmpty(""), // trueisEmpty(33), // true (arguably could be a TypeError)isEmpty([]), // trueisEmpty({}), // trueisEmpty({length: 0, custom_property: []}), // trueisEmpty("Hello"), // falseisEmpty([1,2,3]), // falseisEmpty({test: 1}), // falseisEmpty({length: 3, custom_property: [1,2,3]}) // false

如果只需要处理ECMAscript5浏览器,则可以使用

Object.getOwnPropertyNames
而不是
hasOwnProperty
循环:

if (Object.getOwnPropertyNames(obj).length > 0) return false;

这将确保即使对象仅具有不可枚举的属性,

isEmpty
也仍将为您提供正确的结果。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号