×
文章路径: WEB前端 > JS

Map的JavaScript实现

发表于3年前(Dec 24, 2014 12:47:57 PM)  阅读 677  评论 0

分类: WEB前端 JS

标签: js map map

Java中的Map是一个很实用的集合,习惯了使用Java中的Map,换别的语言没Map时感觉很不爽,以前写Flex AS代码时碰到过用要用Map的情况,不过AS其实有Dictionary字典类可以代替Java中的Map,同时也可以使用对象的属性-值形式来实现Map,在这里JS的Map实现就是使用的对象的属性-值。实现很简单,这里只是为了让Java程序员轻松的编写JS代码。

/*--------------------------------------------------|
| map 1.0 | http://cangzhitao.com 					|
|---------------------------------------------------|
| Copyright (c) 2011- lihui               			|
|                                                   |
  This javascript provided a map like the Map in java
  ,you can use it like this:
  var map = new Map();
  map.put(key, value);
  var value = map.get(key);                   
  
  when the keys is less,it can work well.If it working
  inefficiently,you must choose some other method.
|                                                   |
| Updated: 2011-4-2                                 |
|--------------------------------------------------*/

//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;
};

 

发表评论