Length of a JavaScript object

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

    Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.

    Object.prototype.size = function () {
        var size = 0,
            key;
        for (key in this) {
            if (this.hasOwnProperty(key)) size++;
        }
        return size;
    };
    
    var x = {
        one: 1,
        two: 2,
        three: 3
    };
    
    x.size() === 3;
    

    jsfiddle example: http://jsfiddle.net/qar4j/1/

提交回复
热议问题