确定一个 Javascript 对象有多少个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3154447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:28:42  来源:igfitidea点击:

Determine how many fields a Javascript object has

javascriptmapsize

提问by MatrixFrog

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.)

我有一个 Javascript 对象,我试图将其用作“哈希图”。键总是字符串,所以我认为我不需要像这个 SO question 中描述的那样复杂的东西。(我也不希望键的数量超过大约 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.sizereturns. Of course, you could just do something like:

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

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?

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

采纳答案by Nikita Rybak

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', testwill aslo be counted.

更正:您需要检查myObject.hasOwnProperty(key)每次迭代,因为可以继承属性。例如,如果您在 loop 之前执行此操作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. A lot of javascript is "kind of hacky and roundabout" :)

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

update
Failure example, as requested.


根据要求更新失败示例。

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

The count returned will be 3.

返回的计数将为 3。

回答by Anurag

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

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(..)返回对象上定义的所有键的数组。长度可以被调用。在 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.prototypewith a sizemethod and get the count there. However, a much better solution is to create a HashMaptype interface or use one of the many existing implementations out there, and define sizeon it. Here's one tiny implementation:

请注意,所有对象在 JavaScript 中基本上都是键/值对,并且它们也非常可扩展。你可以Object.prototype用一个size方法扩展它并在那里得到计数。然而,更好的解决方案是创建一个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;
};

Use as (example):

用作(示例):

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

回答by pop850

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

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

nevermind, see this: JavaScript object size

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

回答by Matthew Flaschen

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).

这就是你所能做的。显然,JavaScript 对象不是为此而设计的。这只会给你 Enumerable 属性的数量。试试getObjectSize(Math)