Length of a JavaScript object

前端 未结 30 3053
我在风中等你
我在风中等你 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);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 05:00

    <script>
    myObj = {"key1" : "Hello", "key2" : "Goodbye"};
    var size = Object.keys(myObj).length;
    console.log(size);
    </script>
    
    <p id="myObj">The number of <b>keys</b> in <b>myObj</b> are: <script>document.write(size)</script></p>

    This works for me:

    var size = Object.keys(myObj).length;
    
    0 讨论(0)
  • 2020-11-21 05:00
    const myObject = new Object();
    myObject["firstname"] = "Gareth";
    myObject["lastname"] = "Simpson";
    myObject["age"] = 21;
    
    console.log(Object.keys(myObject).length)
    
    // o/p 3
    
    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-21 05:02

    If you need an associative data structure that exposes its size, better use a map instead of an object.

    const myMap = new Map();
    
    myMap.set("firstname", "Gareth");
    myMap.set("lastname", "Simpson");
    myMap.set("age", 21);
    
    console.log(myMap.size); // 3

    0 讨论(0)
提交回复
热议问题