js实现Set
2021-04-21 13:26
标签:element ++ amp === his 参数 back object col js实现Set 标签:element ++ amp === his 参数 back object col 原文地址:https://www.cnblogs.com/CoderZX/p/12250835.html 1 class MySet {
2 constructor(params) {
3 if (typeof params[Symbol.iterator] !== ‘function‘) {
4 throw new TypeError(‘Set的参数不是一个可以迭代的对象‘)
5 }
6 this._data = []
7 for (var item of params) {
8 this.add(item)
9 }
10 }
11
12 //添加元素
13 add(data) {
14 if(!this.has(data)) {
15 this._data.push(data)
16 }
17 }
18 //判断是否含有该元素
19 has (data) {
20 for (let index = 0; index this._data.length; index++) {
21 const element = this._data[index];
22 if(this.isEqual(element,data)) {
23 return true
24 }
25 }
26 return false
27 }
28 delete (data) {
29 for (let index = 0; index this._data.length; index++) {
30 const element = this._data[index];
31 if(this.isEqual(data,element)) {
32 this._data.splice(index, 1)
33 return true
34 }
35 }
36 return false
37 }
38 forEach(callback) {
39 for (const item of this._data) {
40 callback(item, item, this)
41 }
42 }
43 *[Symbol.iterator] () {
44 for(let item of this._data) {
45 yield item
46 }
47 }
48 clear () {
49 this._data = []
50 }
51 /**
52 * 判断两个数是否相等
53 * @param {*} data1
54 * @param {*} data2
55 */
56
57 isEqual(data1, data2) {
58 if(data1 === 0 && data2 === 0) {
59 return true
60 }
61 return Object.is(data1, data2)
62 }
63 }