Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Aug 1, 2019 · 0 comments
Open

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

wingmeng opened this issue Aug 1, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Aug 1, 2019

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

方法 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant