Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 判断一个对象是否为空对象

判断一个对象是否为空对象

如何判断对象为空?

1.JSON.stringify(target);

const o = {};
console.log(JSON.stringify === "{}");
true;

存在的问题

const o = {
  a: undefined,
  b: function () {},
  c: Symbol(),
};

console.log(JSON.stringify === "{}");
仍为true;

2.for in;

const o = {};
const isEmptyObject = (o) => {
  let bBar = true;
  for (let attr in o) {
    if (o.hasOwnProperty(attr)) {
      bBar = false;
      break;
    }
  }
};

console.log(isEmptyObject(o)); //true

Object.keys(target)

function isEmptyObject(o) {
  return o && typeof o === "object" && Object.keys(o).length === 0;
}

对象中不可枚举属性

3.Object.getOwnPropertyNames(target)

 const o = {
    name: 'yyy'
};
Object.defineProperty(o, 'name', {
    value: '28',
    enumerable: false,
})

console.log(Object.keys(o));  // []
console.log(Object.getOwnPropertyNames(o)); // ['name']

还有key 是Symbol类型的
const s = Symbol();
const o = {
    [s]:28
}

console.log(Object.getOwnPropertyName(o).concat(Object.getOwnPropertySymbols(o)).length === 0);

Reflect.ownKeys(target)

const s = Symbol();
const o = {
  [s]: 233,
};
Object.defineProperty(o, "name", {
  value: "28",
  enumerable: false,
});

console.log(Reflect.ownKeys(o).length === 0);
Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人