Implement your own Map object in JavaScript

Source: Internet
Author: User

 

HashMap plays an irreplaceable role in programming. It provides data storage and reading methods such as m. put (key, value); m. get (key);, which is very convenient. However, such an object is not provided in JavaScript (HTML4.0. The following code is used to create a Map object. I have been using it for many years and it works well for your reference.

 

 

 

1. Map source code

 

 

/** Map is a general map object for storing key value pairs

* @ Param m-default set of properties

*/

Var Map = function (m ){

Var map;

If (typeof m = 'undefined') map = new Array ();

Else map = m;

/**

* Get a list of the keys to check

*/

This. keys = function (){

Var _ keys = new Array ();

For (var _ I in map ){

_ Keys. push (_ I );

}

Return _ keys ;//

};

/**

* Put stores the value in the table

* @ Param key the index in the table where the value will be stored

* @ Param value the value to be stored

*/

This. put = function (key, value ){

Map [key] = value;

};

/**

* Return the value stored in the table

* @ Param key the index of the value to retrieve

*/

This. get = function (key ){

Return map [key];

};

/**

* Remove the value from the table

* @ Param key the index of the value to be removed

*/

This. remove = function (key ){

Map [key] = null;

Delete map [key];

};

/**

* Clear the table

*/

This. clear = function (){

Delete map;

Map = new Array ();

};

}

 

 

 

2. Create a Map object

 

Var m = new Map ();

 

M. put ("id", "1000 ");

 

M. put ("name", "James ");

 

 

 

3. Use www.2cto.com

 

<Div id = "testMap" '> </div>

 

<Script type = 'text/javascript '>

 

Document. getElementById ("testMap"). innerHTML = m. get ("name ");

 

</Script>

 

From the wj800 Column

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.