Set集合:是一种数据的存储结构,适用于不同的场景储存不同的数据
- 主要的功能是存储不重复的数据
set
是通过let a = new Set()
出来- 介绍一下
set
集合的几个实例方法
add()
添加has()
判断此数据是否在集合里面存在delete()
删除该数据size
该属性只读不能更改的
案例:
let arr = new Set([1,2,3,4,5,6,4,5,6])//自动去重
arr.add(1)//重复无法添加
arr.add(10)//可以添加
console.log(arr);
let arr = new Set([1,2,3,4,5,6,4,5,6])
arr.has(1)
console.log(arr.has(1));//已存在返回true
console.log(arr.has(11));//不存在fasle
let arr = new Set([1,2,3,4,5,6,4,5,6])
arr.delete(1);
console.log(arr);
4.
let arr = new Set([1,2,3,4,5,6,4,5,6])
console.log(arr.size);
console.log(arr.size = 10);
console.log(arr);
封装set集合源码
class MySet{
constructor(iter = []){
if(typeof iter[Symbol.iterator] !== "function"){
throw new TypeError(`你数据不是一个可迭代对象`)
}
this._datas = [];
for(const item of iter){
this.add(item)
}
}
add(item){
if(!this.has(item)){
this._datas.push(item)
}
}
has(item){
for(const items of this._datas){
if(this.isE(items,item)){
return true
}
}
return false
}
isE(one,two){
if(one == 0 && two == 0){
return true
}
return Object.is(one,two)
}
get size(){
return this._datas.length
}
clear(){
return this._datas.length = 0;
}
forEach(callback){
for(const ite of this._datas){
callback(ite,ite,this)
}
}
delet(data){
for(let i = 0 ; i < this._datas.length; i++){
if(this.isE(data,this._datas[i])){
this._datas.splice(i,1)
}
}
}
//迭代
*[Symbol.iterator](){
for(const ite of this._datas){
yield ite;
}
}
}