Length of associative arrays in Javascript
Javascript does not have built-in support for associative arrays, only indexed arrays. Yet in Javascript you can quite easily create associative arrays. So what gives? The answer is that in Javascript when you are creating an associative array, you are really create an object and each entry is a member variable in the object. For example:
This will create what looks like an associative array in that you can ask for a value like tempArray['firstKey'] and get back the expected value.
The one big down-side to using and creating associative arrays in this manner is that when you do, none of the "usual" array methods like length, pop, push, etc will work on your array since it's not really an array, it's an object.
So if you are going to use associative arrays in Javascript you'll probably need to create your own functions to replicate these. It's not too hard since the for loops work on these pseudo-arrays. For example, here's a function that will return the length of an associative array in javascript:
var tempArray = new Array(); tempArray['firstKey'] = 'firstValue; tempArray['secondKey'] = 'secondValue'; ... etc
This will create what looks like an associative array in that you can ask for a value like tempArray['firstKey'] and get back the expected value.
The one big down-side to using and creating associative arrays in this manner is that when you do, none of the "usual" array methods like length, pop, push, etc will work on your array since it's not really an array, it's an object.
So if you are going to use associative arrays in Javascript you'll probably need to create your own functions to replicate these. It's not too hard since the for loops work on these pseudo-arrays. For example, here's a function that will return the length of an associative array in javascript:
function getAssocArrayLength(tempArray) {
var result = 0;
for ( tempValue in tempArray ) {
result++;
}
return result;
}
| Rating: | 100% positive, 4 total Votes |
| Categories: | Javascript programming web |
| Added: | on Nov 04, 2008 at 10:13 am |
| Added By: | an anonymous user |
| Searches: | array javascript associ web create |

