Length of a JavaScript object

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

    Here's the most cross-browser solution.

    This is better than the accepted answer because it uses native Object.keys if exists. Thus, it is the fastest for all modern browsers.

    if (!Object.keys) {
        Object.keys = function (obj) {
            var arr = [],
                key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) {
                    arr.push(key);
                }
            }
            return arr;
        };
    }
    
    Object.keys(obj).length;
    

提交回复
热议问题