简体   繁体   English

确定Javascript对象有多少个字段

[英]Determine how many fields a Javascript object has

I have a Javascript object that I'm trying to use as a "hashmap". 我有一个Javascript对象,我试图用作“hashmap”。 The keys are always strings, so I don't think I need anything as sophisticated as what's described in this SO question . 键总是字符串,所以我认为我不需要像SO问题中描述的那样复杂的东西。 (I also don't expect the number of keys to go above about 10 so I'm not particularly concerned with lookups being O(n) vs. O(log n) etc.) (我也不希望密钥的数量超过10,所以我并不特别关注查找是O(n)与O(log n)等。)

The only functionality I want that built-in Javascript objects don't seem to have, is a quick way to figure out the number of key/value pairs in the object, like what Java's Map.size returns. 我想要的内置Javascript对象似乎没有的唯一功能,是一种快速的方法来计算对象中的键/值对的数量,就像Java的Map.size返回的那样。 Of course, you could just do something like: 当然,你可以这样做:

function getObjectSize(myObject) {
  var count=0
  for (var key in myObject)
    count++
  return count
}

but that seems kind of hacky and roundabout. 但这似乎有点hacky和迂回。 Is there a "right way" to get the number of fields in the object? 是否有“正确的方法”来获取对象中的字段数量?

There is an easier way spec'd in ECMAScript 5. 在ECMAScript 5中有一种更简单的方法。

Object.keys(..) returns an array of all keys defined on the object. Object.keys(..)返回在对象上定义的所有键的数组。 Length can be called on that. 可以调用长度。 Try in Chrome: 试试Chrome:

Object.keys({a: 1, b: 2}).length; // 2

Note that all objects are basically key/value pairs in JavaScript, and they are also very extensible. 请注意,所有对象基本上都是JavaScript中的键/值对,并且它们也是非常可扩展的。 You could extend the Object.prototype with a size method and get the count there. 您可以使用size方法扩展Object.prototype并在那里获取计数。 However, a much better solution is to create a HashMap type interface or use one of the many existing implementations out there, and define size on it. 但是,更好的解决方案是创建HashMap类型接口或使用其中的许多现有实现之一,并在其上定义size Here's one tiny implementation: 这是一个很小的实现:

function HashMap() {}

HashMap.prototype.put = function(key, value) {
    this[key] = value;
};

HashMap.prototype.get = function(key) {
    if(typeof this[key] == 'undefined') {
        throw new ReferenceError("key is undefined");
    }
    return this[key];
};

HashMap.prototype.size = function() {
    var count = 0;

    for(var prop in this) {
        // hasOwnProperty check is important because 
        // we don't want to count properties on the prototype chain
        // such as "get", "put", "size", or others.
        if(this.hasOwnProperty(prop) {
            count++;
        }
    }

    return count;
};

Use as ( example ): 用作( 例子 ):

var map = new HashMap();
map.put(someKey, someValue);
map.size();

A correction: you need to check myObject.hasOwnProperty(key) in each iteration, because there're can be inherited attributes. 更正:您需要在每次迭代中检查myObject.hasOwnProperty(key) ,因为可以有继承的属性。 For example, if you do this before loop Object.prototype.test = 'test' , test will aslo be counted. 例如,如果在循环Object.prototype.test = 'test'之前执行此操作,则还将计算test

And talking about your question: you can just define a helper function, if speed doesn't matter. 并且谈论你的问题:如果速度无关紧要,你可以定义辅助函数。 After all, we define helpers for trim function and other simple things. 毕竟,我们为trim函数和其他简单的东西定义帮助器。 A lot of javascript is "kind of hacky and roundabout" :) 很多javascript是“hacky and roundabout”:)

update 更新
Failure example, as requested. 失败示例,根据要求。

Object.prototype.test = 'test';
var x = {};
x['a'] = 1;
x['b'] = 2;

The count returned will be 3. 返回的计数将是3。

you could also just do myObject.length (in arrays) 你也可以只做myObject.length (在数组中)

nevermind, see this: JavaScript object size 没关系,看到这个: JavaScript对象大小

That's all you can do. 这就是你所能做的一切。 Clearly, JavaScript objects are not designed for this. 显然,JavaScript对象不是为此而设计的。 And this will only give you the number of Enumerable properties. 这只会为您提供可枚举属性的数量。 Try getObjectSize(Math) . 试试getObjectSize(Math)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM