The implementation of hash map mapping structure in JavaScript _javascript skills

Source: Internet
Author: User
Tags object object hasownproperty

Hash map is usually used in JavaScript as a simple place to store key-value pairs. However, object is not a real hash map shot, and if used improperly, it may pose potential problems. and JavaScript may not provide a local hash map (at least not cross-browser compatible), there is a better way to declare object properties.

Simple implementation of Hash map:

var hashMap = { 
  set:function (key,value) {This[key] = value}, 
  get:function (key) {return This[key]}, 
  Contains:function (key) {return this. Get (key) = = Null?false:true}, 
  remove:function (key) {delete This[key]} 
} 

Examples of using methods:

Hashmap.set ("name", "John Smith"); 
Hashmap.set ("Age",); 
Hashmap.get ("name");//john Smith 
hashmap.contains ("title");//false 
hashmap.contains ("name");//true 
hashmap.remove ("Age"); 

Problem declaring a member in object

This problem may be due to the inheritance mechanism of the object prototype chain. Take the ToString method, if you use the in operator to determine whether an object exists:

var map = {};
' ToString ' in map; True

Because the in operator looks for the object to exist from all prototypes. To resolve this problem, you can use the hasOwnProperty method to detect whether the object exists:

var map = {};
Map.hasownproperty (' toString '); False

This method can be workplace very normal, but if you define a hasOwnProperty attribute that may be troublesome:

var map = {};
Map.hasownproperty = ' foo ';
Map.hasownproperty (' hasOwnProperty '); TypeError

The quickest way to fix this is to use the native object method.

var map = {};
Map.hasownproperty = ' foo ';
{}.hasownproperty.call (map, ' hasownproperty '); True


This method does not cause any problems, and every time you determine whether an attribute exists in the object, you filter out the method in the prototype chain:

var map = {};
var has = {}.hasownproperty;

for (var key in map) {
 if (Has.call (map, key)) {
  //do Something
 }
}

Naked objects

The trick to creating a real hash map is to solve all of the prototype objects of the Lotus root. We can achieve this by object.create.

var obj = {};
is equivalent to:
var obj = object.create (object.prototype);



In addition, this method allows you to completely discard the prototype, using null directly to inherit.

var map = object.create (null);

Map instanceof Object; False
Object.prototype.isPrototypeOf (map);//False
object.getprototypeof (map);//null


These bare objects (or dictionaries) are ideal for hasp maps. Because there will be no conflict, it will resist any type conversions, such as this would result in an error.

var map = object.create (null);
Map + ""; Typeerror:cannot Convert object to primitive value

There is no reserved word, it is designed for hash map, for example.

var map = object.create (null);
' ToString ' in map; False

Further, the for ... in loop becomes simpler, and we just need to write loops like this.
var map = object.create (null);

for [var key in map] {
 //do something
}

In addition to these differences, it does not differ from the general value of the object store. The object can be serialized, the prototype can be declared and inherited, and the context variable is used equally.

var map = object.create (null);

Object.defineproperties (map, {
 ' foo ': {
  value:1,
  enumerable:true
 },
 ' bar ': {
  value:2,
  enumerable:false
 }
});

Map.foo; 1
map[' Bar '];//2

json.stringify (map);//{"foo": 1}

{}.hasownproperty.call (map, ' foo ');//True
{}.propertyisenumerable.call (map, ' Bar ');//False

Even the variable detection methods mentioned above are equally applicable.

var map = object.create (null);

typeof map; Object
{}.tostring.call (map);//[Object Object]
{}.valueof.call (map);///object {}

Related Article

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.