We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


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
inamorix
korzhik


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 

You need to login to post a comment.