Length of a JavaScript object

前端 未结 30 3094
我在风中等你
我在风中等你 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条回答
  •  闹比i
    闹比i (楼主)
    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()

提交回复
热议问题