javascript——集合类

 1 /**
 2  * Created by Administrator on 2015/4/14.
 3  */
 4 function Set() {
 5     this.values = {};
 6     this.n = 0;
 7     this.add.apply(this, arguments);
 8 }
 9 Set.prototype = {
10     add: function () {
11         for (var i = 0; i < arguments.length; i++) {
12             var val = arguments[i];
13             var str = Set._v2s(val);
14             if (!this.values.hasOwnProperty(str)) {
15                 this.values[str] = val;
16                 this.n++;
17             }
18         }
19         return this;
20     },
21     remove: function () {
22         for (var i = 0; i < arguments.length; i++) {
23             var str = Set._v2s(arguments[i]);
24             if (this.values.hasOwnProperty(str)) {
25                 delete this.values[str];
26                 this.n--;
27             }
28         }
29         return this;
30     },
31     contains: function (value) {
32         return this.values.hasOwnProperty(Set._v2s(value));
33     },
34     size: function () {
35         return this.n;
36     },
37     foreach: function (f, context) {
38         for (var s in this.values) {
39             if (this.values.hasOwnProperty(s)) {
40                 f.call(context, this.values[s]);
41             }
42         }
43     }
44 };
45 Set={
46     //这是一个内部函数,用任意的javascript的值和唯一的字符窜对应连接起来
47     _v2s: function (val) {
48         switch(val){
49             case undefined: return 'u';
50             case  null:return 'n';
51             case true:return 't';
52             case false: return 'f';
53             default :switch (typeof val){
54                 case 'number':return '#'+val;
55                 case  'string':return '"'+val;
56                 default :return '@'+objectId(val);
57             }
58         }
59         //对任意的对象来说都会返回一个字符串
60         //针对不同的字符窜,这个函数会返回不同的字符窜
61         //对于同一个对象多次调用,总是返回相同的字符窜
62         function objectId(o){
63             var prop="|**objectid**|";
64             if(!o.hasOwnProperty(prop)){
65                 o[prop]=Set._v2s.next++;
66             }
67             return o[prop];
68         };
69     }
70 };
71 
72 //设置初始值100
73 Set._v2s.next=100;
原文地址:https://www.cnblogs.com/goesby/p/4426374.html