js实现容器Map
var可以定义一个局部变量,当然如果var定义在最外层的话,就是全局的局部变量,也就算是全局变量了。
this关键字定义的变量准确的说应该算是成员变量。即定义的是调用对象的成员变量。
另外在“类(构造函数)”中,我们通常也会用var定义私有属性,而this定义公共属性。
在该博客中,实现的是容器Map的增加,删除,查询,打印功能。源码如下:
<script> function Map() { var map = function(key, value) {//键值对 this.key = key; this.value = value; } var put = function(key, value) {//添加键值对 this.arr[this.arr.length] = new map(key, value); } var remove = function(key) {//删除key="key"的键值对,返回value值 for (var i = 0; i < this.arr.length; i++) { var temp = this.arr.pop(); if (this.arr[i].key === key) { return this.arr[i].value; } this.arr.push(temp); } return null; } var getKey = function(value) {//返回key对应的value值 for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].value === value) return this.arr[i].key; } return null; } var getValue = function(key) {//返回value对应的key值 for (var i = 0; i < this.arr.length; i++) { if (this.arr[i].key === key) return this.arr[i].value; } return null; } var getSize = function() {//返回容器大小 return this.arr.length; } var show = function() {//打印容器内容 var string = ""; for (var i = 0; i < this.arr.length; i++) { string += (this.arr[i].key + ":" + this.arr[i].value + " "); } alert(string); } this.arr = new Array(); this.remove = remove; this.put = put; this.show = show; this.getKey = getKey; this.getValue = getValue; this.getSize = getSize; } </script> <script type="text/javascript"> var map = new Map(); map.put("num", 1); map.put("red", "2"); alert(map.getKey(1)); alert(map.remove("num")); map.show(); </script>