This article describes the Map class simulated by JS. Share it for your reference, as follows:
According to the properties of map in java, implement key----value saving
1. Use arrays to store data (using closures)
function Map() { var struct = function (key, value) { this.key = key; this.value = value; } var put = function (key, value) { for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].key === key) { this.arr[i].value = value; return; } } this.arr[this.arr.length] = new struct(key, value); } var get = function (key) { for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].key === key) { return this.arr[i].value; } } return null; } var remove = function (key) { var v; for (var i = 0; i < this.arr.length; i++) { v = this.arr.pop(); if (v.key === key) { continue; } this.arr.unshift(v); } } var size = function () { return this.arr.length; } var isEmpty = function () { return this.arr.length <= 0; } this.arr = new Array(); this.get = get; this.put = put; this.remove = remove; this.size = size; this.isEmpty = isEmpty;}2. Use JSON to store data (using prototype expansion method)
function Map() { this.obj = {}; this.count = 0;}Map.prototype.put = function (key, value) { var oldValue = this.obj[key]; if (oldValue == undefined) { this.count++; } this.obj[key] = value;}Map.prototype.get = function (key) { return this.obj[key];}Map.prototype.remove = function (key) { var oldValue = this.obj[key]; if (oldValue != undefined) { this.count--; delete this.obj[key]; }}Map.prototype.size = function () { return this.count;}var map = new Map();map.put("key","map");map.put("key","map1");alert(map.get("key"));//map1map.remove("key");alert(map.get("key"));//undefinedFor more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.