Length of a JavaScript object

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

    If you are using AngularJS 1.x you can do things the AngularJS way by creating a filter and using the code from any of the other examples such as the following:

    // Count the elements in an object
    app.filter('lengthOfObject', function() {
      return function( obj ) {
        var size = 0, key;
        for (key in obj) {
          if (obj.hasOwnProperty(key)) size++;
        }
       return size;
     }
    })
    

    Usage

    In your controller:

    $scope.filterResult = $filter('lengthOfObject')($scope.object)
    

    Or in your view:

    <any ng-expression="object | lengthOfObject"></any>
    
    0 讨论(0)
  • 2020-11-21 05:03

    What about something like this --

    function keyValuePairs() {
        this.length = 0;
        function add(key, value) { this[key] = value; this.length++; }
        function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}
    }
    
    0 讨论(0)
  • 2020-11-21 05:09

    Here's how and don't forget to check that the property is not on the prototype chain:

    var element_count = 0;
    for(var e in myArray)
        if(myArray.hasOwnProperty(e))
            element_count++;
    
    0 讨论(0)
  • 2020-11-21 05:09
    var myObject = new Object();
    myObject["firstname"] = "Gareth";
    myObject["lastname"] = "Simpson";
    myObject["age"] = 21;
    
    1. Object.values(myObject).length
    2. Object.entries(myObject).length
    3. Object.keys(myObject).length
    0 讨论(0)
  • 2020-11-21 05:11

    If you know you don't have to worry about hasOwnProperty checks, you can do this very simply:

    Object.keys(myArray).length
    
    0 讨论(0)
  • 2020-11-21 05:11

    I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:

    var element_count = 0;
    for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }
    

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

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