Posted By

vbert on 02/19/08


Tagged

javascript table array hash associate


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

vbert
korzhik
donesmart


Simple hash table (associate array) in JavaScript


 / Published in: JavaScript
 

/* --==[ EXAMPLE ]==--

var colors = new AArray(); colors.add("k01", {bk:"#fff",tk:"b",it:"hello"});

var oC = colors.get("k01");

var tT = ''; for(K in oC) tT += "[" + K + "]: " + oC[K] + "\n";

tT += "\n\n"; tT += oC.bk + "\n"; tT += oC.tk + "\n"; tT += oC.it + "\n";

alert(tT); */

  1. var Class = {
  2. create: function() {
  3. return function() {
  4. this.initialize.apply(this, arguments);
  5. }
  6. }
  7. }
  8.  
  9. var AArray = Class.create();
  10.  
  11. AArray.prototype = {
  12. AA: {},
  13. initialize: function() {
  14. args = this.initialize.arguments;
  15. if(args.length > 0) {
  16. this.add(args[0], args[1]);
  17. }
  18. },
  19. add: function(key, value) { this.AA[key] = value; },
  20. num: function() { return this.AA.length; },
  21. get: function(key) { return this.AA[key]; },
  22. set: function(key, value) { this.add(key, value); },
  23. test: function() {
  24. var aa = '';
  25. var num = this.num();
  26. for(key in this.AA) aa += '[' + key + ']: ' + this.AA[key] + "\n";
  27. alert(aa);
  28. }
  29. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: birdspider on January 11, 2010

var a = new AArray('a','b');
console.assert(a.get('a') == 'b');
var a1 = new AArray('a','c');
console.assert(a.get('a') == 'b');
console.assert(a1.get('a') == 'c');

line 4 assertion will fail, somehow the 2nd instance influences the first one, I've tried this with my own HashTable class, same results

what do I (we) have overlooked ?

regards

You need to login to post a comment.