Skip to content

Instantly share code, notes, and snippets.

@huguangju
Last active January 19, 2017 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huguangju/262f74a6de2320ac930c7636c6fb086c to your computer and use it in GitHub Desktop.
Save huguangju/262f74a6de2320ac930c7636c6fb086c to your computer and use it in GitHub Desktop.
Is an Object Empty?

在JavaScript中检测对象是否为空?

方式一

isEmptyObject(obj) {
  Object.keys(obj).length === 0;
}

方式二

function isEmptyObject(obj) {
  return Object.getOwnPropertyNames(obj).length === 0;
}

Object.getOwnPropertyNames()方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性)组成的数组。

方式三

// 缓存hasOwnProperty方法
var hasOwnProperty = Object.prototype.hasOwnProperty;

function isEmpty(obj) {

    // null 和 undefined 是空的
    if (obj == null) return true;

    // 假设它有一个length属性且值不为0,那它就是为空的。
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // 如果它不是对象,在这里认为它是空(虽然它可能是任意 *非* 空的值)。
    // 这种情况它为不为空?取决于你的应用。
    if (typeof obj !== "object") return true;

    // 另外,它是否有自已的属性(排除从原型链继承的属性)?
    // 注意这种方式不能避免IE9以下的toString和valueOf枚举bug
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return false;
    }

    return true;
}

来自 http://stackoverflow.com/a/4994244/4723163

方式四

jQuery的isEmptyObject方法

function isEmptyObject( obj ) {
  var name;

  for ( name in obj ) {
    return false;
  }
  return true;
}

https://github.com/jquery/jquery/blob/1b9575b9d14399e9426b9eacdd92b3717846c3f2/src/core.js#L257-L267

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