Friday, July 18, 2014

javascript object hashmap associative array

i use javascript quite a bit and i program for work in Java, so I wanted to mash them both together and as a result was reading about Rhino, which allows javascript to call Java classes and methods. And I was looking through some sample code and the following blew my mind:
var f = new File(arguments[0]);
var o = {}
var line;
while ((line = f.readLine()) != null) {
 // Use JavaScript objects' inherent nature as an associative array to provide uniqueness
 o[line] = true;
}
for (i in o) {
 print(i);
}
i didn't understand the code!  after some investigation, i found that the base javascript object acts like a HashMap, a TreeSet and an associative array. check out the code below:
<script>
 var tt = {hair:"black,cat,dog",eyes:"brown"};
 console.log(tt);
 tt["eyes"] = true;
 tt[""] = true;
 tt[null] = true;
 console.log(tt);
 console.log(tt[0]);  // should print hair
 console.log(tt[0][1]);  // should print cat
</script>
it's output is:
Object { hair="black,cat,dog", eyes="brown"}
Object { hair="black,cat,dog", eyes=true, =true, null=true}
undefined
TypeError: tt[0] is undefined
the only drawback is that the last two don't work, you can't access it like an array, even though internally it's an array of arrays. anyways that explains how they were able to get unique lines, they were checking the values against the javascript objects keys (which have to be unique).

No comments:

Post a Comment