Javascript 检查字典对象的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3337367/
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 04:14:07  来源:igfitidea点击:

Checking length of dictionary object

javascript

提问by PositiveGuy

I'm trying to check the length here. Tried count. Is there something I'm missing?

我想在这里检查长度。试过数。有什么我想念的吗?

var dNames = {}; 
dNames = GetAllNames();

for (var i = 0, l = dName.length; i < l; i++) 
{
        alert("Name: " + dName[i].name);
}

dNames holds name/value pairs. I know that dNames has values in that object but it's still completely skipping over that and when I alert out even dName.length obviously that's not how to do this...so not sure. Looked it up on the web. Could not find anything on this.

dNames 保存名称/值对。我知道 dNames 在那个对象中有值,但它仍然完全跳过那个,当我警告甚至 dName.length 显然这不是如何做到这一点......所以不确定。在网上查了一下。找不到任何关于此的信息。

回答by Greg Hornby

What I do is use Object.keys() to return a list of all the keys and then get the length of that

我所做的是使用 Object.keys() 返回所有键的列表,然后获取它的长度

Object.keys(dictionary).length

回答by sberry

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

回答by meder omuraliev

This question is confusing. A regular object, {}doesn't have a lengthproperty unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).

这个问题令人困惑。常规对象{}没有length属性,除非您打算制作自己的函数构造函数来生成具有它的自定义对象(在这种情况下,您没有指定)。

Meaning, you have to get the "length" by a for..instatement on the object, since lengthis not set, and increment a counter.

意思是,您必须通过for..in对象上的语句获取“长度” ,因为length未设置,并增加计数器。

I'm confused as to why you need the length. Are you manually setting 0on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';. If the latter, again, why the need for length?

我很困惑为什么你需要length. 您是手动设置0对象,还是依赖自定义字符串键?例如obj['foo'] = 'bar';。如果是后者,为什么需要长度?

Edit #1: Why can't you just do this?

编辑#1:你为什么不能这样做?

list = [ {name:'john'}, {name:'bob'} ];

Then iterate over list? The lengthis already set.

然后遍历列表?在length已经设置。

回答by Cees Timmerman

Count and show keys in a dictionary (run in console):

计算并显示字典中的键(在控制台中运行):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

示例输出:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

简单的计数功能:

function size_dict(d){c=0; for (i in d) ++c; return c}