Length of a JavaScript object

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

提交回复
热议问题