Length of a JavaScript object

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

    @palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".

    And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:

    JavaScript “Associative Arrays” Considered Harmful

    But according to all this, the accepted answer itself is bad practice?

    Specify a prototype size() function for Object

    If anything else has been added to Object .prototype, then the suggested code will fail:

    <script type="text/javascript">
    Object.prototype.size = function () {
      var len = this.length ? --this.length : -1;
        for (var k in this)
          len++;
      return len;
    }
    Object.prototype.size2 = function () {
      var len = this.length ? --this.length : -1;
        for (var k in this)
          len++;
      return len;
    }
    var myArray = new Object();
    myArray["firstname"] = "Gareth";
    myArray["lastname"] = "Simpson";
    myArray["age"] = 21;
    alert("age is " + myArray["age"]);
    alert("length is " + myArray.size());
    </script>
    

    I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.

    0 讨论(0)
  • 2020-11-21 04:56

    We can find the length of Object by using:

    Object.values(myObject).length
    
    0 讨论(0)
  • 2020-11-21 04:56

    Use:

    var myArray = new Object();
    myArray["firstname"] = "Gareth";
    myArray["lastname"] = "Simpson";
    myArray["age"] = 21;
    obj = Object.keys(myArray).length;
    console.log(obj)

    0 讨论(0)
  • 2020-11-21 04:56

    Use Object.keys(myObject).length to get the length of object/array

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

    The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
    
        // Get the size of an object
        const myObj = {}
        var size = Object.size(myObj);

    There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.


    Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes:

    var size = Object.keys(myObj).length;
    

    This doesn't have to modify any existing prototype since Object.keys() is now built-in.

    Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.

    Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites.

    Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols.

      var person = {
          [Symbol('name')]: 'John Doe',
          [Symbol('age')]: 33,
          "occupation": "Programmer"
        };
        
        const propOwn = Object.getOwnPropertyNames(person);
        console.log(propOwn.length); // 1
        
        let propSymb = Object.getOwnPropertySymbols(person);
        console.log(propSymb.length); // 2

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