Visitar URL original
第 76 期(ECMAScript-语法):如何判断空对象 · Issue #79 · fezaoduke/fe-practice-hard · GitHub
Skip to content

第 76 期(ECMAScript-语法):如何判断空对象 #79

Description

@wingmeng

如何判断一个对象是否为空对象?即是否是 {} 这样的对象。

方法 1:ES6 Object.keys 判断长度

const isObject = obj => Object.prototype.toString.call(obj) === '[object Object]';
const isEmptyObject = obj => isObject(obj) ? Object.keys(obj).length === 0 : false;

isEmptyObject({});  // true
isEmptyObject({a: 1});  // false

方法 2:for in 循环判断

const isEmptyObject = obj => {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false
    }
  }

  return true;
};

isEmptyObject({});  // true
isEmptyObject({a: 1});  // false

方法 3:方法 2 的变种

Object.defineProperty(Object.prototype, 'isEmptyObject', {
  writable: false,
  enumerable: false,
  configurable: false,
  value: function() {
    for (let key in this) {
      if (this.hasOwnProperty(key)) {
        return false
      }
    }

    return true;
  }
});

// 注意:字面量对象调用时要将表达式用小括号包起来
({}.isEmptyObject());  // true
({a: 1}.isEmptyObject());  // false

let obj = {};
obj.isEmptyObject();  // true

方法 4:JSON.stringify 转换判断

const isEmptyObject = obj => JSON.stringify(obj) === '{}';

isEmptyObject({});  // true
isEmptyObject({a: 1});  // false

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions