判断对象是否为空对象
转载:https://blog.****.net/kongjiea/article/details/78851221
1.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
</style>
<script src="https://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var obj={"a":1};
//兼容IE8(此法还是很巧妙的,将对象字符串化,然后再对两个字符串做比较)
if(JSON.stringify(obj) == "{}"){
console.log('JSON.stringify方法:is empty');
}else{
console.log('JSON.stringify方法:not empty');
}
//兼容IE9
if(Object.getOwnPropertyNames(obj).length == 0){
console.log("Object.getOwnPropertyNames方法:is empty")
}else{
console.log("Object.getOwnPropertyNames方法:not empty")
}
//或者 兼容IE9
if(Object.keys(obj).length == 0){
console.log("Object.keys方法:is empty")
}else{
console.log("Object.keys方法:not empty")
}
//循环 for in 的方法(如果自己使用时,可以将return的值改为true 和 false ,然后通过if的判断条件走相应的部分)
function isEmptyObj(obj){
for(key in obj){
if(key){
return "for循环方法:not empty"
}
}
return "for循环方法:is empty"
}
console.log(isEmptyObj(obj));
</script>
</body>
</html>
2.运行结果
3.说明:
(1)在Google浏览器这样的标准浏览器下都可运行,但低版本IE不支持Object.getOwnPropertyNames和Object.keys会出现报错;
(2)建议使用for in方法 和 JSON.stringify方法;