views:

1515

answers:

3

Dear All I am Using Hashtable in javascript, I want to show the values of following in Hashtable

    one   -[1,10,5]
    two   -[2]
    three -[3,30,300 ..etc]

I have found following code it work for following data

   one  -[1]
   two  -[2]  
   three-[3]

How to assign one-[1,2] values to hash table and how to access it ? any idea

<script type="text/javascript">

function Hash()
{
    this.length = 0;
    this.items = new Array();
    for (var i = 0; i < arguments.length; i += 2) {
     if (typeof(arguments[i + 1]) != 'undefined') {
      this.items[arguments[i]] = arguments[i + 1];
      this.length++;
     }
    }

    this.removeItem = function(in_key)
    {
     var tmp_value;
     if (typeof(this.items[in_key]) != 'undefined') {
      this.length--;
      var tmp_value = this.items[in_key];
      delete this.items[in_key];
     }

     return tmp_value;
    }

    this.getItem = function(in_key) {
     return this.items[in_key];
    }

    this.setItem = function(in_key, in_value)
    {
     if (typeof(in_value) != 'undefined') {
      if (typeof(this.items[in_key]) == 'undefined') {
       this.length++;
      }

      this.items[in_key] = in_value;
     }

     return in_value;
    }

    this.hasItem = function(in_key)
    {
     return typeof(this.items[in_key]) != 'undefined';
    }
}

var myHash = new Hash('one',1,'two', 2, 'three',3 );

for (var i in myHash.items) {
    alert('key is: ' + i + ', value is: ' + myHash.items[i]);
}


</script>

How to do it any help?

+1  A: 

Using the function above, you would do:

var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);

Of course, the following would also work:

var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];

since all objects in Javascript are hashtables! It would however be harder to iterate over since using foreach(var item in object) would also get you all its functions etc., but that might be enough depending on your needs.

roryf
+1  A: 

If all you want to do is store some static values into a lookup table, you can use json to do it compactly:

var table = { one: [1,10,5], two: [2], three: [3, 30, 300] }

And then access them using Javascript's associative array syntax:

alert(table['one']); // will alert with [1,10,5]
alert(table['one'][1]); // will alert with 10
scraimer
That's an object literal, not JSON. JSON is a data format.
Tim Down
A: 

You could use my JavaScript hash table implementation, jshashtable. It allows any object to be used as a key, not just strings.

Tim Down