Js judges whether the object is empty and whether there is an attribute on the object

1. The method of judging whether the object is empty:

const obj = {};

1.通过JSON.stringify()将对象转为字符串进行判断
console.log(JSON.stringify(obj) === '{}'); // true

2.通过es6的Object.keys()方法将对象属性转换成数组进行判断
console.log(Object.keys(obj).length === 0); // true

3.通过for in 循环进行判断
function isEmptyObj () {
  for (const key in obj) {
    return false;
  }
  return true;
}
console.log(isEmptyObj()); // true

2. Determine whether an attribute exists on the object:

const obj = {};

1.通过in运算符进行判断(in会判断继承过来的属性)
console.log('name' in obj); // false
console.log('toString' in obj); // true

2.通过es6新增方法Reflect.has()判断(和in的功能完全一样)
Reflect.has(obj, 'name') // false
Reflect.has(obj, 'toString') // true

3.通过hasOwnProperty()判断(只会检测对象自身的属性,不会检测继承的属性)
obj.hasOwnProperty('name') // false
obj.hasOwnProperty('toString') // false

4.通过Object.prototype.hasOwnProperty.call()判断
Object.prototype.hasOwnProperty.call(obj, 'name') // false
Object.prototype.hasOwnProperty.call(obj, 'toString') // false

5.通过es6方法Object.hasOwn()判断(用来代替Object.prototype.hasOwnProperty.call())
Object.hasOwn(obj, 'name') // false
Object.hasOwn(obj, 'toString') // false

Guess you like

Origin blog.csdn.net/qq_35408366/article/details/130503858