·  JavaScript – Syntax – Collections – Hash

 

- Info:

  - This tutorial shows how to use hash in Java Script.

  - Hash is implemented by creating object whose property names serve as keys.

  - This tutorial is based on http://www.mojavelinux.com/articles/javascript_hashes.html

 

- Using Array:

  - Create D\Temp\JavaScript\Test.html

 

    Test.html     

    <script> 

   

      //CREATE HASH.

      array = new Array();

      array['one'] = 1;

      array['two'] = 2;

     

      //DISPLAY HASH.

      for (i in array) {

        console.log('key is: ' + i + ', value is: ' + array[i]);

      }

   

    </script>

 

- Using Object:

  - Create D\Temp\JavaScript\Test.html

 

    Test.html     

    <script> 

   

      //CREATE EMPTY HASH AND ADD ELEMENTS.

      hash = {};

      hash.a = 1;

      hash.b = 2;

      hash.c = 'hello';

     

      //CREATE HASH WITH STRING LITERAL.

      hash = {

        a : 1,

        b : 2,

        c : 'hello'

      }

     

      //DISPLAY ELEMENTS.

      for (key in hash){

        console.log(key+"="+hash[key]+"\n"); 

      }

     

      //DISPLAY ELEMENTS.

      console.log(hash.a);

      console.log(hash['a']);

   

    </script>