Length of a JavaScript object

前端 未结 30 3054
我在风中等你
我在风中等你 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 05:11

    You can always do Object.getOwnPropertyNames(myObject).length to get the same result as [].length would give for normal array.

    0 讨论(0)
  • 2020-11-21 05:12

    The simplest way is like this:

    Object.keys(myobject).length
    

    Where myobject is the object of what you want the length of.

    0 讨论(0)
  • 2020-11-21 05:12

    Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)

    Object.size = (obj) ->
      size = 0
      size++ for own key of obj
      size
    
    0 讨论(0)
  • 2020-11-21 05:13

    If we have the hash

    hash = {"a" : "b", "c": "d"};

    we can get the length using the length of the keys which is the length of the hash:

    keys(hash).length

    0 讨论(0)
  • 2020-11-21 05:13

    A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:

    Object.defineProperty(Object.prototype, "length", {
        get: function () {
            return Object.keys(this).length;
        }
    });
    

    And you can just use it like so:

    var myObj = { 'key': 'value' };
    myObj.length;
    

    It would give 1.

    0 讨论(0)
  • 2020-11-21 05:15

    This method gets all your object's property names in an array, so you can get the length of that array which is equal to your object's keys' length.

    Object.getOwnPropertyNames({"hi":"Hi","msg":"Message"}).length; // => 2
    
    0 讨论(0)
提交回复
热议问题