Is object empty?

This question already has an answer here:

  • How do I test for an empty JavaScript object? 39 answers

  • I'm assuming that by empty you mean "has no properties of its own".

    // Speed up calls to hasOwnProperty
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    
    function isEmpty(obj) {
    
        // null and undefined are "empty"
        if (obj == null) return true;
    
        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;
    
        // If it isn't an object at this point
        // it is empty, but it can't be anything *but* empty
        // Is it empty?  Depends on your application.
        if (typeof obj !== "object") return true;
    
        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
            if (hasOwnProperty.call(obj, key)) return false;
        }
    
        return true;
    }
    

    Examples:

    isEmpty(""), // true
    isEmpty(33), // true (arguably could be a TypeError)
    isEmpty([]), // true
    isEmpty({}), // true
    isEmpty({length: 0, custom_property: []}), // true
    
    isEmpty("Hello"), // false
    isEmpty([1,2,3]), // false
    isEmpty({test: 1}), // false
    isEmpty({length: 3, custom_property: [1,2,3]}) // false
    

    If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames instead of the hasOwnProperty loop:

    if (Object.getOwnPropertyNames(obj).length > 0) return false;
    

    This will ensure that even if the object only has non-enumerable properties isEmpty will still give you the correct results.


    对于ECMAScript5(尽管在所有浏览器中都不支持),您可以使用:

    Object.keys(obj).length === 0
    

    EDIT : This answer is deprecated unless you can't use ES5 solution for some reason. Note that ES5 support is widespread these days, and even if it weren't, one can always use Babel. YMMV of course.


    Easy and cross-browser way is by using jQuery.isEmptyObject :

    if ($.isEmptyObject(obj))
    {
        // do something
    }
    

    More: http://api.jquery.com/jQuery.isEmptyObject/

    You need jquery though.

    链接地址: http://www.djcxy.com/p/31740.html

    上一篇: Object.getOwnPropertyNames与Object.keys

    下一篇: 对象是空的吗?