Home Web Front-end JS Tutorial js imitates java's Map collection to implement functions

js imitates java's Map collection to implement functions

Nov 10, 2016 pm 02:41 PM

java.util 中的集合类包含 Java 中某些最常用的类。最常用的集合类是 List 和 Map。List 的具体实现包括 ArrayList 和 Vector,它们是可变大小的列表,比较适合构建、存储和操作任何类型对象元素列表。List 适用于按数值索引访问元素的情形。

Map 提供了一个更通用的元素存储方法。Map 集合类用于存储元素对(称作“键”和“值”),其中每个键映射到一个值。从概念上而言,您可以将 List 看作是具有数值键的 Map。而实际上,除了 List 和 Map 都在定义 java.util 中外,两者并没有直接的联系。本文将着重介绍核心 Java 发行套件中附带的 Map,同时还将介绍如何采用或实现更适用于您应用程序特定数据的专用 Map。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />  
<title>测试map</title>  
</head>  
<style type="text/css">  
</style>  
<script type="text/javascript">  
/*  
 * Map对象,实现Map功能  
 * size() 获取Map元素个数  
 * isEmpty() 判断Map是否为空  
 * clear() 删除Map所有元素  
 * put(key, value) 向Map中增加元素(key, value)   
 * remove(key) 删除指定key的元素,成功返回true,失败返回false  
 * get(key) 获取指定key的元素值value,失败返回null  
 * element(index) 获取指定索引的元素(使用element.key,element.value获取key和value),失败返回null  
 * containsKey(key) 判断Map中是否含有指定key的元素  
 * containsValue(value) 判断Map中是否含有指定value的元素  
 * keys() 获取Map中所有key的数组(array)  
 * values() 获取Map中所有value的数组(array)  
 *  
 */ 
function Map(){  
    this.elements = new Array();  
    
    //获取Map元素个数  
    this.size = function() {  
        return this.elements.length;  
    },  
    
    //判断Map是否为空  
    this.isEmpty = function() {  
        return (this.elements.length < 1);  
    },  
    
    //删除Map所有元素  
    this.clear = function() {  
        this.elements = new Array();  
    },  
    
    //向Map中增加元素(key, value)   
    this.put = function(_key, _value) {  
        if (this.containsKey(_key) == true) {  
            if(this.containsValue(_value)){  
                if(this.remove(_key) == true){  
                    this.elements.push( {  
                        key : _key,  
                        value : _value  
                    });  
                }  
            }else{  
                this.elements.push( {  
                    key : _key,  
                    value : _value  
                });  
            }  
        } else {  
            this.elements.push( {  
                key : _key,  
                value : _value  
            });  
        }  
    },  
    
    //删除指定key的元素,成功返回true,失败返回false  
    this.remove = function(_key) {  
        var bln = false;  
        try {    
            for (i = 0; i < this.elements.length; i++) {    
                if (this.elements[i].key == _key){  
                    this.elements.splice(i, 1);  
                    return true;  
                }  
            }  
        }catch(e){  
            bln = false;    
        }  
        return bln;  
    },  
    
    //获取指定key的元素值value,失败返回null  
    this.get = function(_key) {  
        try{    
            for (i = 0; i < this.elements.length; i++) {  
                if (this.elements[i].key == _key) {  
                    return this.elements[i].value;  
                }  
            }  
        }catch(e) {  
            return null;    
        }  
    },  
    
    //获取指定索引的元素(使用element.key,element.value获取key和value),失败返回null  
    this.element = function(_index) {  
        if (_index < 0 || _index >= this.elements.length){  
            return null;  
        }  
        return this.elements[_index];  
    },  
    
    //判断Map中是否含有指定key的元素  
    this.containsKey = function(_key) {  
        var bln = false;  
        try {  
            for (i = 0; i < this.elements.length; i++) {    
                if (this.elements[i].key == _key){  
                    bln = true;  
                }  
            }  
        }catch(e) {  
            bln = false;    
        }  
        return bln;  
    },  
      
    //判断Map中是否含有指定value的元素  
    this.containsValue = function(_value) {  
        var bln = false;  
        try {  
            for (i = 0; i < this.elements.length; i++) {    
                if (this.elements[i].value == _value){  
                    bln = true;  
                }  
            }  
        }catch(e) {  
            bln = false;    
        }  
        return bln;  
    },  
    
    //获取Map中所有key的数组(array)  
    this.keys = function() {  
        var arr = new Array();  
        for (i = 0; i < this.elements.length; i++) {    
            arr.push(this.elements[i].key);  
        }  
        return arr;  
    },  
   
    //获取Map中所有value的数组(array)  
    this.values = function() {  
        var arr = new Array();  
        for (i = 0; i < this.elements.length; i++) {    
            arr.push(this.elements[i].value);  
        }  
        return arr;  
    };  
}  
//测试map  
alert(&#39;测试map&#39;);  
var map=new Map();  
map.put(0,0);  
map.put(1,1);  
map.put(2,2);  
alert(&#39;map的大小为:&#39;+map.size());  
for(var i=0;i<map.size();i++){  
    alert(&#39;map的key&#39;+i+&#39;对应的value值为&#39;+map.get(i));  
}  
alert(&#39;获取map中不存在的键&#39;+map.get(&#39;获取map中不存在的键&#39;));  
alert(&#39;map中的所有键的长度&#39;+map.keys().length);  
for(var i=0;i<map.keys().lenght;i++){  
    alert(&#39;map中的键值&#39;+map.keys()[i]);  
}  
alert(&#39;map中的所有的value值的长度&#39;+map.values().length);  
for(var i=0;i<map.values().length;i++){  
    alert(&#39;map中的value的值&#39;+map.values()[i]);  
}  
alert(&#39;判断map中的值value是否存在3&#39;+map.containsValue(3));  
</script>  
<body>  
测试map  
</body>  
</html>
Copy after login


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles