Sunday, August 21, 2011

JavaScript Associative Array

Although an associative array doesn’t technically exist in JavaScript it can be achieved via

   1: var myArray = new Array();



   2: myArray["index1"] = "Value1";



   3: myArray["index2"] = "Value2";




This is all fine and dandy till you realise that the length property will always return zero ( 0 )





   1: //always displays zero



   2: alert(myArray.length);




This can be highly annoying considering the fact that you might need to do work based on whether or not the array has any values. The only solution I could find is to create a static helper method. So in my OO nature I created:





   1: function Helper() { }



   2: Helper.arraySize = function (associativeArray) {



   3:                                 var count = 0;



   4:                                 for (var i in associativeArray) {



   5:                                     count++;



   6:                                 }



   7:                                 return count;



   8:                             }




So now if I need to check the length of an “associative array” I can do so via:





   1: // Displays 2



   2: var size = Helper.arraySize(myArray);



   3: alert(size);




Might seem like a long way round but it is the only method I found thus far that facilitates my use case. Don’t forget to include the JS file if you have put it in a separate file Winking smile



References:





Technorati Tags:


Windows Live Tags: JavaScript


WordPress Tags: JavaScript

No comments:

Post a Comment