Length of a JavaScript object

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

    Here is a completely different solution that will only work in more modern browsers (Internet Explorer 9+, Chrome, Firefox 4+, Opera 11.60+, and Safari 5.1+)

    See this jsFiddle.

    Setup your associative array class

    /**
     * @constructor
     */
    AssociativeArray = function () {};
    
    // Make the length property work
    Object.defineProperty(AssociativeArray.prototype, "length", {
        get: function () {
            var count = 0;
            for (var key in this) {
                if (this.hasOwnProperty(key))
                    count++;
            }
            return count;
        }
    });
    

    Now you can use this code as follows...

    var a1 = new AssociativeArray();
    a1["prop1"] = "test";
    a1["prop2"] = 1234;
    a1["prop3"] = "something else";
    alert("Length of array is " + a1.length);
    

提交回复
热议问题