日期:2014-05-16 浏览次数:20364 次
<script type="text/javascript"><!-- /** * @author: 丸子 * @date: 2011-1-8 * map对象类,提供了put,get,remove,size,isEmpty等方法 */ function Map() { /** * 构造函数 * @param {} key * @param {} value */ var struct = function(key, value) { this.key = key; this.value = value; } /** * 添加key对应的值,如果key已经存在则直接更新对应的值 * @param {} key * @param {} value */ var put = function(key, value) { for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].key === key) { this.arr[i].value = value; return; } } this.arr[this.arr.length] = new struct(key, value); } /** * 获取key对应的值 * @param {} key * @return {} */ var get = function(key) { for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].key === key) { return this.arr[i].value; } } return null; } /** * 移除key对应的值 * @param {} key */ var remove = function(key) { var v; for (var i = 0; i < this.arr.length; i++) { v = this.arr.pop(); if (v.key === key) { continue; } this.arr.unshift(v); } } /** * 获取map对象的长度 * @return {} */ var size = function() { return this.arr.length; } /** * 判断map对象是否为空 * @return {} */ var isEmpty = function() { return this.arr.length <= 0; } this.arr = new Array(); this.get = get; this.put = put; this.remove = remove; this.size = size; this.isEmpty = isEmpty; } // --> </script> <script type="text/javascript"><!-- var map = new Map(); map.put("re","redhacker"); map.put("do","douguoqiang"); map.put("gq","dougq"); alert("map的大小为:" + map.size()) alert("key为re的map中存储的对象为:" + map.get("do")); map.remove("re"); alert("移除key为re的对象后,获取key为re的map中存储的对象为:" + map.get("do")); alert("map移除一个元素后的大小为:" + map.size()); alert("map是否是一个空map:" + map.isEmpty()); // --> </script>