Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何判断一个空对象 #15

Open
ckinmind opened this issue Feb 18, 2017 · 2 comments
Open

如何判断一个空对象 #15

ckinmind opened this issue Feb 18, 2017 · 2 comments

Comments

@ckinmind
Copy link
Owner

ckinmind commented Feb 18, 2017

在应用中消息那一块有一个判断对象是否为空的地方,发现怎么也无法生效,判断方法如下

let data = {};
if(!data){  
   ...
}

if里面无法生效

上面判断空对象的方法是错误的,我搜索找到了几种判断空对象的方法如下:

  1. JSON.stringify , 参考资料: JavaScript 如何判断一个对象{}是否为空对象
var data = {};  
JSON.stringify(data) == "{}" // true 
  1. Object.keys, 参考资料:js如何判断一个变量等于空对象
function isEmpty(value) {
    return Object.keys(value).length === 0;
}

Object.keys() 方法会返回一个由给定对象的所有可枚举自身属性的属性名组成的数组
参考资料:MDN: Object.keys()

@Pomelo1213
Copy link

不太对,第一个方法有问题,stringify会忽略function
例如:

let obj = {
  func: function(){}
}
console.log(JSON.stringify(obj) === "{}"   //true

@ckinmind
Copy link
Owner Author

@Pomelo1213 是的,但是简单对象(无function)的可以

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants