Reputation: 11711
I have the following object:
var l={"a":1,"b":2,"c":5};
I want to get the length of this
alert(l.length);
but that returns undefined
. Obviously I'm looking to get 3
as the answer.
Upvotes: 5
Views: 248
Reputation: 104760
function count(O){
for(var p in O){
if(O.hasOwnProperty(p))++cnt;
}
return cnt;
}
count(l);
Upvotes: 1
Reputation: 97555
You can count the number of entries in an object using Object.keys()
, which returns an array of the keys in the object:
var l = {a: 1, b: 2, c: 3};
Object.keys(l).length;
However, it might be more efficient (and cross browser) to implement your own property:
Object.length = function(obj) {
var i = 0;
for(var key in obj) i++;
return i;
}
Object.length(l);
Note that although I could have defined the function as Object.prototype.length
, allowing you to write l.length()
, I didn't, because that would fail if your object container the key length
.
Upvotes: 11