js无法直接比较一个对象是否为空( obj === {}
永远为 false
),原因是js在对比两者时是比对的两者的内存地址,而 {}
放在js引擎新分配的内存地址中,故而两者永远不相等。
Object.getOwnPropertyNames()
1
| let isEmpty = (Object.getOwnPropertyNames(obj).length === 0);
|
Object.keys()
1
| let isEmpty = (Object.keys(obj).length === 0);
|
JSON.stringify()
1
| const isEmpty = obj => JSON.stringify(obj) === "{}"
|
for…in
1 2 3 4 5 6
| const isEmpty = obj => { for (var key in obj) { return false; } return true; }
|
Reflect.ownKeys()
1
| const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
|
jQuery中的isEmptyObject()
1
| let isEmpty = $.isEmptyObject(obj);
|
updated on: 2021-12-06