Alex Rivera | Logout

javascript associative array length using jQuery

Asked 2010-03-08T15:01:46.433
9

I am using javascript associative array like:

var testarray = [];
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

I am also using jquery alongside. How can I check length of this associative array using jquery or any other method? Basically i want to check whether this array is empty or not.

Thank you.

Edit
Report

2 Answers

13

This gives you the length of your associative array:

Object.keys(testarray).length
answered 2013-07-16T10:48:20.917
0

You can loop through the properties to count them:

var cnt = 0;
for (i in testarray) cnt++;
alert(cnt);

Note that the for (... in ...) will also loop items added by a prototype, so you might want to count only the items added after that:

var cnt = 0;
for (i in testarray) if (testarray.hasOwnProperty(i)) cnt++;
alert(cnt);

If you just want to check if there are any properties, you can exit out of the loop after the first item:

var empty = true;
for (i in testarray) if (testarray.hasOwnProperty(i)) { empty = false; break; }
alert(empty);
answered 2010-03-08T15:10:03.283

Your Answer