您的位置:首页 > Web前端 > JavaScript

JavaScript 字典(Dictionary)

2017-06-09 17:40 148 查看
TypeScript方式实现源码

//  set(key,value):向字典中添加新元素。
//  remove(key):通过使用键值来从字典中移除键值对应的数据值。
//  has(key):如果某个键值存在于这个字典中,则返回true,反之则返回false。
//  get(key):通过键值查找特定的数值并返回。
//  clear():将这个字典中的所有元素全部删除。
//  size():返回字典所包含元素的数量。与数组的length属性类似。
//  keys():将字典所包含的所有键名以数组形式返回。
//  values():将字典所包含的所有数值以数组形式返回。


1 /**
2  * 字典
3  * @desc 与Set类相似,ECMAScript 6同样包含了一个Map类的实现,即我们所说的字典
4  */
5 var Dictionary = (function () {
6     function Dictionary() {
7         this.items = {};
8     }
9     Dictionary.prototype.set = function (key, value) {
10         this.items[key] = value;
11     };
12     Dictionary.prototype.remove = function (key) {
13         if (this.has[key]) {
14             delete this.items[key];
15             return true;
16         }
17         else {
18             return false;
19         }
20     };
21     Dictionary.prototype.has = function (key) {
22         return key in this.items;
23     };
24     Dictionary.prototype.get = function (key) {
25         return this.has(key) ? this.items[key] : undefined;
26     };
27     Dictionary.prototype.clear = function () {
28         this.items = {};
29     };
30     Dictionary.prototype.size = function () {
31         var count = 0;
32         for (var prop in this.items) {
33             if (this.items.hasOwnProperty(prop))
34                 ++count; //{7}
35         }
36         return count;
37     };
38     Dictionary.prototype.keys = function () {
39         var values = [];
40         for (var k in this.items) {
41             if (this.has(k)) {
42                 values.push(k);
43             }
44         }
45         return values;
46     };
47     Dictionary.prototype.values = function () {
48         var values = [];
49         for (var k in this.items) {
50             if (this.has(k)) {
51                 values.push(this.items[k]);
52             }
53         }
54         return values;
55     };
56     Dictionary.prototype.getItems = function () {
57         return this.items;
58     };
59     return Dictionary;
60 }());


字典 Dictionary
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: