Length of a JavaScript object

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

    
    

提交回复
热议问题