Length of a JavaScript object

前端 未结 30 3161
我在风中等你
我在风中等你 2020-11-21 04:35

I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["         


        
相关标签:
30条回答
  • 2020-11-21 04:52

    Simply use this to get the length:

    Object.keys(myObject).length
    
    0 讨论(0)
  • 2020-11-21 04:53

    For some cases it is better to just store the size in a separate variable. Especially, if you're adding to the array by one element in one place and can easily increment the size. It would obviously work much faster if you need to check the size often.

    0 讨论(0)
  • 2020-11-21 04:53

    A variation on some of the above is:

    var objLength = function(obj){    
        var key,len=0;
        for(key in obj){
            len += Number( obj.hasOwnProperty(key) );
        }
        return len;
    };
    

    It is a bit more elegant way to integrate hasOwnProp.

    0 讨论(0)
  • 2020-11-21 04:54

    To not mess with the prototype or other code, you could build and extend your own object:

    function Hash(){
        var length=0;
        this.add = function(key, val){
             if(this[key] == undefined)
             {
               length++;
             }
             this[key]=val;
        }; 
        this.length = function(){
            return length;
        };
    }
    
    myArray = new Hash();
    myArray.add("lastname", "Simpson");
    myArray.add("age", 21);
    alert(myArray.length()); // will alert 2
    

    If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.

    Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)

    0 讨论(0)
  • 2020-11-21 04:54

    You can simply use Object.keys(obj).length on any object to get its length. Object.keys returns an array containing all of the object keys (properties) which can come in handy for finding the length of that object using the length of the corresponding array. You can even write a function for this. Let's get creative and write a method for it as well (along with a more convienient getter property):

    function objLength(obj)
    {
      return Object.keys(obj).length;
    }
    
    console.log(objLength({a:1, b:"summit", c:"nonsense"}));
    
    // Works perfectly fine
    var obj = new Object();
    obj['fish'] = 30;
    obj['nullified content'] = null;
    console.log(objLength(obj));
    
    // It also works your way, which is creating it using the Object constructor
    Object.prototype.getLength = function() {
       return Object.keys(this).length;
    }
    console.log(obj.getLength());
    
    // You can also write it as a method, which is more efficient as done so above
    
    Object.defineProperty(Object.prototype, "length", {get:function(){
        return Object.keys(this).length;
    }});
    console.log(obj.length);
    
    // probably the most effictive approach is done so and demonstrated above which sets a getter property called "length" for objects which returns the equivalent value of getLength(this) or this.getLength()

    0 讨论(0)
  • 2020-11-21 04:55

    Updated: If you're using Underscore.js (recommended, it's lightweight!), then you can just do

    _.size({one : 1, two : 2, three : 3});
    => 3
    

    If not, and you don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:

    $.assocArraySize = function(obj) {
        // http://stackoverflow.com/a/6700/11236
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
    };
    
    0 讨论(0)
提交回复
热议问题