如何获取 JavaScript 哈希表计数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8702219/
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
How to get JavaScript hash table count?
提问by rsk82
Possible Duplicate:
Length of Javascript Associative Array
可能的重复:
Javascript 关联数组的长度
hash_table = {a: 131, b: 222, c:313}
The length method is not working of course since it will be confused with a key.
length 方法当然不起作用,因为它会与键混淆。
So how do I do it?
那么我该怎么做呢?
回答by qiao
Object.keys
will return all the keys in the object as a list, then use length to get the length.
Object.keys
将对象中的所有键作为列表返回,然后使用长度来获取长度。
example:
例子:
Object.keys(hash_table).length
NOTE that this is ECMA 5 and may not be available in some browsers. see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keysfor full document.
请注意,这是 ECMA 5,可能在某些浏览器中不可用。有关完整文档,请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys。
回答by simonecampora
var count = 0;
for ( property in hash_table ) count++;