JS自定义对象实现Java中Map对象功能的方法_javascript技巧

WBOY
Release: 2016-05-16 16:19:01
Original
1602 people have browsed it

本文实例讲述了JS自定义对象实现Java中Map对象功能的方法。分享给大家供大家参考。具体分析如下:

Java中有集合,Map等对象存储工具类,这些对象使用简易,但是在JavaScript中,你只能使用Array对象。

这里我创建一个自定义对象,这个对象内包含一个数组来存储数据,数据对象是一个Key,可以实际存储的内容!

这里Key,你要使用String类型,和Java一样,你可以进行一些增加,删除,修改,获得的操作。

使用很简单,我先把工具类给大家看下:

复制代码代码如下:
/**
* @version 1.0
* 用于实现页面 Map 对象,Key只能是String,对象随意
*/
var Map = function(){
this._entrys = new Array();

this.put = function(key, value){
if (key == null || key == undefined) {
return;
}
var index = this._getIndex(key);
if (index == -1) {
var entry = new Object();
entry.key = key;
entry.value = value;
this._entrys[this._entrys.length] = entry;
}else{
this._entrys[index].value = value;
}
};
this.get = function(key){
var index = this._getIndex(key);
return (index != -1) ? this._entrys[index].value : null;
};
this.remove = function(key){
var index = this._getIndex(key);
if (index != -1) {
this._entrys.splice(index, 1);
}
};
this.clear = function(){
this._entrys.length = 0;;
};
this.contains = function(key){
var index = this._getIndex(key);
return (index != -1) ? true : false;
};
this.getCount = function(){
return this._entrys.length;
};
this.getEntrys = function(){
return this._entrys;
};
this._getIndex = function(key){
if (key == null || key == undefined) {
return -1;
}
var _length = this._entrys.length;
for (var i = 0; i var entry = this._entrys[i];
if (entry == null || entry == undefined) {
continue;
}
if (entry.key === key) {//equal
return i;
}
}
return -1;
};
}


如果你不懂Js中对象的创建等一些基础知识,自己可以网上查一下。
复制代码代码如下:
// 自定义Map对象
var map = new Map();
map.put("a","a");
alert(map.get("a"));
map.put("a","b");
alert(map.get("a"));


先弹出 a 后面弹出 b ,因为后面的会覆盖前面的!

其他方法大家自己写写看!

希望本文所述对大家的javascript程序设计有所帮助。

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
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!