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
�
References:
- http://stackoverflow.com/questions/5223/length-of-javascript-associative-array
- http://www.pageresource.com/jscript/jarray2.htm
- http://www.mojavelinux.com/articles/javascript_hashes.html
- http://blog.anselmbradford.com/2009/04/09/object-oriented-javascript-tip-creating-static-methods-instance-methods/
Technorati Tags: JavaScript
Windows Live Tags: JavaScript
WordPress Tags: JavaScript
No comments:
Post a Comment