共计 806 个字符,预计需要花费 3 分钟才能阅读完成。
在前端,我们通常需要用 JS 处理一些从服务器返回的数据,例如简单的数据清洗、对数据格式做细微的调整等等,这些需求在 java 中借助集合通常很容易完成,但 JS 原生不提供类似 java 中的集合,这时,我们可以利用 JS 中的原生数组和 Object 对象来封装 List、Map、Set 这些集合,下面依次说明如何封装这些集合。
List
List 结构本身可以看作一个线性数组,因此可以利用数组来封装,首先,定义 List 中的数组和各类方法。
function List(){this.values = new Array(); | |
this.add = function(a){this.values.push(a); | |
} | |
this.get = function(index){if(index >= this.values.length){console.error("index is out range of the max index"); | |
}else{return values[index]; | |
} | |
} | |
...... | |
} |
Map
Map 用来存储 key-Value,与 JS 中的 Object 对象很相似,因此,可以通过封装 Object 对象,定义一系列方法来构造 Map。
function Map(){this.objs = {}; | |
this.put = function(key ,value){this.objs[key] = value; | |
} | |
this.get = function(key){if(key in this.objs){return this.objs[key]; | |
}else{console.debug("this key is not in the Map"); | |
} | |
} | |
this.keys = function(){var a = new Array(); | |
for(var b in this.objs){a.push(b); | |
} | |
return a; | |
} | |
this.delete = function(key){delete this.objs[key]; | |
} | |
} |
正文完
发表至: javascript
2019-05-05