开发者

Checking length of dictionary object [duplicate]

This question already has answers here: Length of a JavaScript object (43 answers) Closed 2 years ago.

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.


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

Object.keys(dictionary).length


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

alert(count);


This question is confusing. A regular object, {} doesn't have a length property 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 ).

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

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

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

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

Then iterate over list? The length is already set.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜