es6新增了类的概念,同时也新增了Set这个新的数据结构,
尝试使用类来实现一个类似于Set的集合。
包括has(),add(),delete(),clear(),leys(),values().forEach()这几个方法;
思来想去,觉得好像用到set的地方并不多,数组去重时会用一下,其他地方好像都没怎么用,
我的理解就是set数据结构就是一个所有元素都是唯一的的一个集合;
它接收一个可迭代对象 [iterable]
以下是代码实现:
class SetTest {
constructor(params = []) {
this.items = {}
this.size = 0
this.init(params)
}
init(params) {
params.forEach(element => {
this.add(element)
});
}
has(val) {
return this.items.hasOwnProperty(val)
}
add(val) {
if (!this.has(val)) {
this.items[val] = val
this.size++
return true
}
return false
}
delete(val) {
if (this.has(val)) {
delete this.items[val]
this.size--
return true
}
return false
}
clear() {
this.items = {}
this.size = 0
}
keys() {
return Object.keys(this.items)
}
values() {
return Object.values(this.items)
}
forEach(fn, context = this) {
for (let i = 0; i < this.size; i++) {
let item = Object.keys(this.items)[i];
fn.call(context, item, item, this.items);
}
}
}
测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./set.js"></script>
</head>
<body>
<script>
const mySet = new SetTest([1, 2, 3, 6, '5', 2, 6, 5])
console.log(mySet.has('b'), 'has');
console.log(mySet.add('b'), 'add');
console.log(mySet.delete(1), 'delete1');
console.log(mySet.keys(), 'keys');
mySet.forEach((item, index, ary) => {
console.log(item);
console.log(index);
console.log(ary);
})
</script>
</body>
</html>