CPHPython CPHPython - 2 months ago 8
Javascript Question

Using hash tables in Javascript: is an array of arrays adequate?

I need an hash table in Javascript, i.e. to implement an associative array which maps keys (strings) to values (in my case, these are several integer arrays). I realized that this kind of approach is not commonly used, or at least I haven't found it on the web yet:



var hash = ['s0'];
for (var i = 5; i >= 1; i--) {
var r = Math.floor(Math.random() * 3);
hash['s'+i] = [r, r*2, r^2];
}
console.log(hash);
hash.forEach(function (v, i, a) {
document.getElementById('foreach').innerHTML += i + ' => ' + v + '<br>';
})
for (var i = 5; i >= 1; i--) {
var key = 's'+i;
document.getElementById('for').innerHTML += key + ' => [' + hash[key].toString() + ']<br>';
}

<p id="foreach">forEach (val,index):<br/></p>
<p id="for">for:<br/></p>





Perhaps due to the fact that the declared array seems to not be correctly mapped after I add the new values (open your console and click the
+
button, you can see the values are there even when it displays
[s1]
). The
forEach
keeps assuming the array only has one value, but if I access any of those keys directly, e.g.
hash['s3']
, the respective array is returned.

Therefore, am I doing something wrong? Should I even use this approach?




If objects in JSON are more appropriate for this case, what is the best way to implement something simple and similar to the example above?

Furthermore, if
key_string
is the string I want as key,
hash.push(key_string: val_array)
fails because it is not a "formal parameter". However by doing something like:

hash.push({'key':key_string,'value':val_array})


How can I access one of those arrays in the simplest way possible through its associated key?

Answer

Why can't you use a JavaScript Map()?

MDN JavaScript Reference: Map

I modified your code below to use a Map instead of an Array:

var map = new Map();
for (var i = 5; i >= 1; i--) {
  var r = Math.floor(Math.random() * 3);
  map.set('s'+i, [r, r*2, r^2]);
}
console.log(map);
map.forEach(function (v, i, m) {
  document.getElementById('foreach').innerHTML += i + ' => ' + v + '<br>';
})
for (var i = 5; i >= 1; i--) {
  var key = 's'+i;
  document.getElementById('for').innerHTML += key + ' => [' + map.get(key).toString() + ']<br>';
}
<p id="foreach">forEach (val,index):<br/></p>
<p id="for">for:<br/></p>