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

🎁第7期第3题:如何判断一个对象是否为空对象? #46

Open
LinDaiDai opened this issue Jul 8, 2020 · 0 comments
Open

Comments

@LinDaiDai
Copy link
Owner

空对象?咳咳,就是这个:

let obj = {}
  1. for...in...
function isEmptyObj (obj) {
	for (i in obj) {
		return false
	}
	return true;
}
console.log(isEmptyObj(obj)); // true

不过这种方法貌似有一个弊端,因为for...in...是会把对象原型链上的属性也列举出来,例如下面这样就会判断错误:

function isEmptyObj (obj) {
  for (i in obj) {
    return false
  }
  return true;
}
let obj = {};
obj.__proto__.num = 'dsfdf'
console.log(isEmptyObj(obj)); // false
  1. JSON.stringify()

😂,这个是呆呆很久之前用的一种方法:

function isEmptyObj (obj) {
	return JSON.stringify(obj) === '{}';
}
console.log(isEmptyObj(obj)); // true
  1. Object.keys()
function isEmptyObj (obj) {
	return Object.keys(obj).length === 0;
}
console.log(isEmptyObj(obj)); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant