|
 
- 注册时间
- 2005-3-9
- 威望
- 1952
- 阅读权限
- 150
- 积分
- 4347
- 帖子
- 1577
- 精华
- 9
- UID
- 24714
- 状态
- 当前离线
|
来个“月版”的HashTable ^^
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
- <HTML>
- <HEAD>
- <TITLE> New Document </TITLE>
- <META NAME="Generator" CONTENT="EditPlus">
- <META NAME="Author" CONTENT="">
- <META NAME="Keywords" CONTENT="">
- <META NAME="Description" CONTENT="">
- <SCRIPT LANGUAGE="JavaScript">
- <!--
- function HashTable()
- {
- //private fields
- var items = [];
- //public methods
- this.count = function(){return items.length};
- this.any = function(closure, set){
-
- set = set || false;
- closure = closure || function(){};
- var args = Array.apply(this, arguments).slice(2);
- for(var i = 0;i < items.length;i++){
- var rval = closure.apply(this, [items[i].key, items[i].value].concat(args).concat(i));
- if(rval || rval === 0){
- if(set && set.put)
- set.put(rval);
- else
- return rval;
- }
- }
- return set;
- }
- this.each = function(closure){
- var set = [];
- set.put = set.push;
- return this.any(closure, set);
- }
- this.add = function(key, value){
- var item = items[this.any(function(k, v, i){if(k == key) return i})] || {key:key, value:value};
- items.push(item);
- }
- this.getValue = function(key){
- return this.any(function(k, v){if(k == key) return v});
- }
- this.containsKey = function(key){
- return this.any(function(k, v){if(k == key) return true});
- }
- this.containsValue = function(value){
- return this.any(function(k, v){if(v == value) return true});
- }
- this.remove = function(key){
- items = this.each(function(k, v){return k != key ? {key:k, value:v} : null});
- }
- this.clear = function(){items.length = 0};
-
- this.keys = function(){
- return this.each(function(k, v){return k});
- }
- this.values = function(){
- return this.each(function(k, v){return v});
- }
- this.isEmpty = function(){return this.count() == 0};
- this.indexOfKey=function(key)
- {
- var idx = this.any(function(k, v, i){if(k == key) return i});
- return idx || -1;
- }
- this.indexOfValue=function(value)
- {
- var idx = this.any(function(k, v, i){if(v == value) return i});
- return idx || -1;
- }
-
- this.toArray = function()
- {
- return items;
- }
- this.iterator = function()
- {
- var idx = 0, it = {};
- it.next = function(){
- return items[idx++];
- }
- it.hasNext = function(){
- return idx == items.length;
- }
- return it;
- }
- }
- var my=new HashTable();
- my.add("name","cxp");
- my.add("age",22);
- my.add("sex","boy");
- var arr = my.toArray();
-
- for(var i in arr)
- {
- alert("Key:"+arr[i].key+",Value:"+arr[i].value);
- }
-
- my.remove("age");
- alert(my.keys());
- alert(my.values());
- var it = my.iterator();
- var o;
- while(o = it.next())
- {
- alert("Key:"+o.key+",Value:"+o.value);
- }
- //-->
- </SCRIPT>
- </HEAD>
- <BODY>
-
- </BODY>
- </HTML>
复制代码运行代码另存代码 |
|