Length of a JavaScript object

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

    If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:

    1. Run either Object.keys() to get an array that contains the names of only those properties that are enumerable or Object.getOwnPropertyNames() if you want to also include the names of properties that are not enumerable.
    2. Get the .length property of that array.

    If you need to do this more than once, you could wrap this logic in a function:

    function size(obj, enumerablesOnly) {
        return enumerablesOnly === false ?
            Object.getOwnPropertyNames(obj).length :
            Object.keys(obj).length;
    }
    

    How to use this particular function:

    var myObj = Object.create({}, {
        getFoo: {},
        setFoo: {}
    });
    myObj.Foo = 12;
    
    var myArr = [1,2,5,4,8,15];
    
    console.log(size(myObj));        // Output : 1
    console.log(size(myObj, true));  // Output : 1
    console.log(size(myObj, false)); // Output : 3
    console.log(size(myArr));        // Output : 6
    console.log(size(myArr, true));  // Output : 6
    console.log(size(myArr, false)); // Output : 7
    

    See also this Fiddle for a demo.

提交回复
热议问题