Number of elements in a javascript object

后端 未结 6 2148
借酒劲吻你
借酒劲吻你 2020-12-12 17:46

Is there a way to get (from somewhere) the number of elements in a javascript object?? (i.e. constant-time complexity).

I cant find a property or method that retriev

6条回答
  •  一整个雨季
    2020-12-12 18:30

    Although JS implementations might keep track of such a value internally, there's no standard way to get it.

    In the past, Mozilla's Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5.

    For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():

    function countProperties(obj) {
        var count = 0;
    
        for(var prop in obj) {
            if(obj.hasOwnProperty(prop))
                ++count;
        }
    
        return count;
    }
    

    In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)

    function countProperties(obj) {
        return Object.keys(obj).length;
    }
    

    Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length).

    If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.

提交回复
热议问题