确定 Javascript 对象有多少个字段

发布于 2024-09-07 13:50:56 字数 591 浏览 5 评论 0原文

我有一个 Javascript 对象,我试图将其用作“哈希图”。键始终是字符串,因此我认为我不需要像这个问题。 (我也不期望键的数量超过 10 个,所以我并不特别关心查找的 O(n) 与 O(log n) 等)

我想要内置 Javascript 的唯一功能对象似乎没有,是一种快速计算对象中键/值对数量的方法,就像 Java 的 Map.size 返回。当然,你可以这样做:

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

但这似乎有点老套和迂回。是否有“正确的方法”来获取对象中的字段数量?

I have a Javascript object that I'm trying to use as a "hashmap". The keys are always strings, so I don't think I need anything as sophisticated as what's described in this SO question. (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.)

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. 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. Is there a "right way" to get the number of fields in the object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

水染的天色ゝ 2024-09-14 13:50:56

ECMAScript 5 中指定了一种更简单的方法。

Object.keys(..) 返回对象上定义的所有键的数组。长度可以称之为。在 Chrome 中尝试:

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

请注意,所有对象基本上都是 JavaScript 中的键/值对,并且它们也具有很强的可扩展性。您可以使用 size 方法扩展 Object.prototype 并在那里获取计数。然而,更好的解决方案是创建一个 HashMap 类型接口或使用现有的许多实现之一,并在其上定义 size 。这是一个微小的实现:

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

用作(示例):

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

There is an easier way spec'd in ECMAScript 5.

Object.keys(..) returns an array of all keys defined on the object. Length can be called on that. Try in 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. You could extend the Object.prototype with a size method and get the count there. 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. 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();
哆啦不做梦 2024-09-14 13:50:56

更正:您需要在每次迭代中检查 myObject.hasOwnProperty(key) ,因为可以继承属性。例如,如果您在循环 Object.prototype.test = 'test' 之前执行此操作,test 也会被计数。

并谈论您的问题:如果速度不重要,您可以定义一个辅助函数。毕竟,我们为修剪函数和其他简单的事情定义了助手。很多 javascript 都是“有点 hacky 和迂回”:)

更新
根据要求,失败示例。

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

返回的计数将为 3。

A correction: you need to check myObject.hasOwnProperty(key) in each iteration, because there're can be inherited attributes. For example, if you do this before loop Object.prototype.test = 'test', test will aslo be counted.

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. A lot of javascript is "kind of 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.

柳絮泡泡 2024-09-14 13:50:56

你也可以只做 myObject.length (在数组中)

没关系,看看这个:JavaScript 对象大小

you could also just do myObject.length (in arrays)

nevermind, see this: JavaScript object size

萤火眠眠 2024-09-14 13:50:56

这就是你所能做的。显然,JavaScript 对象并不是为此而设计的。这只会为您提供可枚举属性的数量。尝试getObjectSize(Math)

That's all you can do. Clearly, JavaScript objects are not designed for this. And this will only give you the number of Enumerable properties. Try getObjectSize(Math).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文