文章目录
- 一、Set
- 声明一个 set
- 元素个数
- 添加新的元素
- 删除元素
- 检测是否有,查询元素
- 清空
- 遍历
- 二、Set 实践
-
- 三、Map
- 声明 Map
- 添加元素
- 大小
- 删除
- 获取
- 清空
- 遍历
一、Set
1. 声明一个 set
let s = new Set();
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
console.log(s,typeof s);
console.log(s2);

2. 元素个数
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
console.log(s2.size);

3. 添加新的元素
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
s2.add('喜事儿');
console.log(s2);

4. 删除元素
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
s2.delete('坏事儿');
console.log(s2);

5. 检测是否有,查询元素
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
console.log(s2.has('糟心事'));

6. 清空
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
s2.clear();
console.log(s2);

7. 遍历
let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);
for(let v of s2){
console.log(v);
}

二、Set 实践
let arr = [1,2,3,4,5,4,3,2,1];
let arr2 = [4,5,6,5,6];
1. 数组去重
let result = [...new Set(arr)];
console.log(result);

2. 交集
let result = [...new Set(arr)].filter(item => {
let s2 = new Set(arr2);// 4 5 6
if(s2.has(item)){
return true;
}else{
return false;
}
});
console.log(result);
//简写
let result = [...new Set(arr)].filter(item => new Set(arr2).has(item));
console.log(result);

3. 并集
let union = [...new Set([...arr, ...arr2])];
console.log(union);

4. 差集
let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)));
console.log(diff);

三、Map
1. 声明 Map
let m = new Map();
console.log(m);

2. 添加元素
m.set('name','Jack');
m.set('work', function(){
console.log("我要好好学习!!");
});
let key = {
school : '这是一个学校名称'
};
m.set(key, ['北京','上海','深圳']);
console.log(m);

3. 大小
let m = new Map();
m.set('name','Jack');
m.set('work', function(){
console.log("我要好好学习!!");
});
let key = {
school : '这是一个学校名称'
};
m.set(key, ['北京','上海','深圳']);
console.log(m.size);

4. 删除
m.delete('name');
console.log(m);

5. 获取
console.log(m.get('work'));
console.log(m.get(key));

6. 清空
m.clear();
console.log(m);

7. 遍历
for(let v of m){
console.log(v);
}

还没有评论,来说两句吧...