我有一个JavaScript对象。是否有一种内置或公认的最佳实践方法来获取此对象的长度?

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

当前回答

如果您使用的是AngularJS 1.x,则可以通过创建过滤器并使用以下任何其他示例中的代码以AngularJS的方式进行操作:

// 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;
 }
})

用法

在控制器中:

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

或者在您看来:

<any ng-expression="object | lengthOfObject"></any>

其他回答

该解决方案适用于多种情况和跨浏览器:

Code

var getTotal = function(collection) {

    var length = collection['length'];
    var isArrayObject =  typeof length == 'number' && length >= 0 && length <= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER

    if(isArrayObject) {
        return collection['length'];
    }

    i= 0;
    for(var key in collection) {
        if (collection.hasOwnProperty(key)) {
            i++;
        }
    }

    return i;
};

数据示例:

// case 1
var a = new Object();
a["firstname"] = "Gareth";
a["lastname"] = "Simpson";
a["age"] = 21;

//case 2
var b = [1,2,3];

// case 3
var c = {};
c[0] = 1;
c.two = 2;

用法

getLength(a); // 3
getLength(b); // 3
getLength(c); // 2

您可以简单地对任何对象使用Object.keys(obj).length来获取其长度。keys返回一个包含所有对象键(财产)的数组,使用相应数组的长度可以方便地找到该对象的长度。你甚至可以为此编写一个函数。让我们发挥创意,并为其编写一个方法(以及更方便的getter属性):

函数objLength(obj){return Object.keys(obj).length;}console.log(objLength({a:1,b:“summit”,c:“无意义”}));//工作非常好var obj=新对象();obj['fish']=30;obj['ullified content']=null;console.log(objLength(obj));//它也按照您的方式工作,即使用Object构造函数创建它Object.prototype.getLength=函数(){return Object.keys(this).length;}console.log(obj.getLength());//你也可以把它写成一个方法,这样做效率更高Object.defineProperty(Object.prototype,“length”,{get:function(){return Object.keys(this).length;}});console.log(对象长度);//可能最有效的方法是这样做的,并在上面进行了演示,它为对象设置了一个名为“length”的getter属性,该属性返回getLength(this)或this.getLength()的等效值

如果我们有哈希

哈希={“a”:“b”,“c”:“d”};

我们可以使用密钥的长度来获得长度,即哈希的长度:

密钥(哈希).length

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

console.log(Object.keys(myObject).length)

// o/p 3

实现这一点的一个好方法(仅限Internet Explorer 9+)是在长度属性上定义一个神奇的getter:

Object.defineProperty(Object.prototype, "length", {
    get: function () {
        return Object.keys(this).length;
    }
});

你可以这样使用它:

var myObj = { 'key': 'value' };
myObj.length;

它会给出1。