Javascript_object (based on map exercises)

Source: Internet
Author: User

JavaScript is not as handy in programming as Java, providing a lot of APIs for development to call directly, but the bottom layer also encapsulates a lot of tools for developers to write methods to implement,

Take map For example, write simple additions and deletions to simulate the map in Java:

function Map () {
var obj = {}; Create an Object

To bind a value to a map
This.put = function (key,value) {
Obj[key] = value;
}

Get the number of maps
var count = 0;
This.size = function () {
var count = 0;
for (var i in obj) {
Count + +;
}
return count;
}

Get value based on key (very common, used today when writing Java)
This.get = function (key) {
if (Obj[key] | | obj[key] = = 0 | | obj[key] = = = False) {
return Obj[key];
}else{
return null;
}
}

removing values
This.remove = function (key) {
if (Obj[key] | | obj[key] = = 0 | | obj[key] = = = False) {
Delete Obj[key];
}
}
  

The key (value) that traverses the map;
This.foreach = function (fn) {//FN callback function
for (var i in obj) {
FN (I,obj[i]);
}
}
}

var m = new Map (); Instantiate a map
M.put ("001", false); To add a key value to a map
M.put ("002", true);
M.put ("003", "sz");

To test
Alert (M.size ());
Alert (M.get ("003"));
Alert (M.remove ("001"));

M.foreach (function (key,value) {
Alert (key + ":" + value);
})

Javascript_object (based on map exercises)

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.