Home > Web Front-end > JS Tutorial > body text

JavaScript implements the Map structure in Java

高洛峰
Release: 2016-11-28 14:58:45
Original
1234 people have browsed it

Map in Java is a very practical collection. I am used to using Map in Java. I feel very uncomfortable when I switch to another language without Map. I have encountered situations where Map is needed when writing Flex AS code before, but AS actually There is a Dictionary dictionary class that can replace Map in Java. At the same time, Map can also be implemented using the attribute-value form of an object. Here, the Map implementation of JS uses the attribute-value of the object. The implementation is very simple, this is just to allow Java programmers to easily write JS code.

//construction
function Map() {
        this.obj = new Object();
};
 
//add a key-value
Map.prototype.put = function(key, value) {
        this.obj[key] = value;
};
 
//get a value by a key,if don't exist,return undefined
Map.prototype.get = function(key) {
        return this.obj[key];
};
 
//remove a value by a key
Map.prototype.remove = function(key) {
        if(this.get(key)==undefined) {
                return;
        }
        delete this.obj[key];
};
 
//clear the map
Map.prototype.clear = function() {
        this.obj = new Object();
};
 
//get the size
Map.prototype.size = function() {
        var ary = this.keys();
        return ary.length;
};
 
//get all keys
Map.prototype.keys = function() {
        var ary = new Array();
        for(var temp in this.obj) {
                ary.push(temp);
        }
        return ary;
};
 
//get all values
Map.prototype.values = function() {
        var ary = new Array();
        for(var temp in this.obj) {
                ary.push(this.obj[temp]);
        }
        return ary;
};
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!