functionisObjectValueEqual (a, b) { if (a === b) { returntrue; }
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) { returnfalse; }
var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b);
if (aProps.length !== bProps.length) { returnfalse; }
for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; var propA = a[propName]; var propB = b[propName];
if (!isObjectValueEqual(propA, propB)) { returnfalse; } }
returntrue; }
如何判空对象
JSON.stringify:可以使对象序列化,转化成字符串
1 2 3 4
const obj = {};
console.log(JSON.stringify(obj) === '{}') // true
缺点:undefined、任意的函数以及 symbol 值,在序列化过程中会被忽略(出现在非数组对象的属性值中时)或者被转换成 null(出现在数组中时)。函数、undefined 被单独转换时,会返回 undefined,如JSON.stringify(function(){}) or JSON.stringify(undefined).
1 2 3 4 5 6 7 8
let symbolValue = Symbol() const obj = { a: undefined, b: symbolValue, c: function (){} } console.log('JSON' + JSON.stringify(obj));
for in遍历
1 2 3 4 5 6 7 8 9 10 11 12
const obj2 = {} Object.prototype.a = 1 functionisEmpty (obj) { let flag = true for (i in obj) { flag = false break } return flag } console.log(isEmpty(obj2)); //false
缺点:会遍历原型上的属性,需要使用hasOwnProperty方法
for in + hasOwnProperty() 方法来检查属性是否是对象自身的属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
const obj2 = {} Object.prototype.a = 1 functionisEmpty (obj) { let flag = true for (i in obj) { if (obj.hasOwnProperty(obj)) { flag = false break } } return flag } console.log(isEmpty(obj2)); //true