Associative arrays with count() and clear() methods. The quickest solution

Javascript does not have (by default) any counting and clearing methods for associative arrays (based on JS object). This article shows probably the quickest way to add a little bit more functionality to Javascript arrays. The same, as can be found in other programming languages.

Here’s the code

[code language=”javascript”]
var dict =
{
/**
* Functions for counting elements and clering our so-called
* associative array.
*/
count: function()
{
var cnt = -2; //To compensate ‘count’ and ‘clear’ methods;

for (var k in this) cnt++

return cnt;
},
clear: function() {for(var k in this) if(k != ‘clear’ && k != ‘sizeOf’) delete this[k]}
};
[/code]

After incorporating above code into any of your scripts you can call it like that:

[code language=”javascript”]
alert(dict.count());
dict.clear();
[/code]

This is a 2-minute, dirty and not perfect at all solution, that I wanted to remember. But, this certainly isn’t something to be proud of.

If you need a better solution (that introduces many other functionalities and adds them to base object definition, so every associative array shares it) then you should consider using “JavaScript zArray Library”, which you can find here or by googling around.

Leave a Reply