I need get js object properties count.
I search and found solutions like this:
var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
var count = 0;
for (var k in foo) {
if (foo.hasOwnProperty(k)) {
++count;
}
}
Question: why needed condition if (foo.hasOwnProperty(k)) { ?
I think that this code must work good always, without this condition also.
I am wrong?
See this: How to efficiently count the number of keys/properties of an object in JavaScript?
yes, the hasOwnProperty method is really reduntant here.
Anyway, why you need to get properties count? I'm afraid you are solving something a bad way.
Some objects have properties added by the system (ie prototype).
You normally don't want to count those. The condition you ask about will make sure you only count properties belonging to your object itself.
So if you intend to make a function that will return the count for any object, its probably better to include the condition, otherwise you don't necessarily need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With