Counting Associative Array Length in JavaScript
February 26, 2013 1:47 pm Leave your thoughtsBefore we look at the code snippets, yes there is no such thing as associative array in JavaScript, they are all objects. But really, a lot of people search for “how do we get JavaScript associative array length?” so I might as well publish this short post.
So say we have an object cars, containing the key “honda”, “toyota”, “nissan” with their respective values; we can’t just get cars.length, that wouldn’t work.
We actually have to iterate over the objects and maintain the count. In the next snippet I will give both example with and without jQuery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var test = { "honda": "integra", "toyota": "86", "nissan": "GTR" } //with jQuery var count = 0 $.each(test, function(index, value) { count++; }) console.log(count); //will show 3 //without jQuery var count = 0 for (x in test) { count++; } console.log(count) //will show 3 |
I hope the above helped or refreshed your memory.
Tags: javascript, jQueryCategorised in: Coding, Javascript