tags:

views:

40

answers:

2

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.

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

alert(count);
sberry2A
ok so you have to iterate through...no way to do it off a custom object that has name/values?
CoffeeAddict
I don't **think** there is. Make sure to check the "hasOwnProperty" to stop iteration down up the prototype chain and only check properties.
sberry2A
Thanks..I'm more an OOP guy, but starting to get used to JS more.
CoffeeAddict
This is the most reliable way to do this in JS. See sberry's note about `hasOwnProperty` as well. The key, @coffeeaddict, is that a JS object can behave like, but is not fundamentally the same as, a "collection" object in other languages. Hence the puzzling lack of a convenience method for getting the total number of properties on it.
quixoto
A: 

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.

meder
So an array has a count property...because probably that for is built into the JS native type?
CoffeeAddict
`[]` has `length`, `{}` doesnt. use a `for` loop with `length` for `[]` and a `for..in` for `{}`.
meder
To answer your question yea, it's confusing because I'm not a JS guy, I'm a C# guy. So I needed to check the length of my dictionary to test whether it had any objects in it. For regular error handling I guess you'd just check for null on a dictionary but just wanted to see how many returned and was added to my dictionary. So the problem was not how to iterate, just see how to get the count which I just thought you could with a dictionary type (nvp) object so-to-say.
CoffeeAddict
yes, I'm using obj['foo'] = 'bar'; type of deal to get something that acts as a dictionary.
CoffeeAddict