目录
一、Set集合
1.操作方法
2.set案例
二、Map()集合
1、操作方法
2.Map()的遍历
(1)for...of实现遍历
(2)forEach()遍历
一、Set集合
Set集合
:是一种数据结构,结构类似于数组,且没有重复的值。主要用于数组去重,字符串去重。
1.操作方法
(1)add()
用于添加值,返回set结构本身:
let set = new Set();
set.add('1').add('2').add('3');
console.log(set)//set(3){'1','2','3'}
需要注意的是:拓展运算符(...)
可以将Set
值扩展出来。
例如将上面的字符串分别以字符和数组的扩展
console.log(...set);//1 2 3
console.log([...set])//['1','2','3']
(2)delete()
用于删除值,并返回一个boolean表示是否删除成功
console.log(set.delete('2'))//true
console.log(set)//Set(2) { '1', '3' }
(3)has()
用于判断指定值值是否存在,并返回一个Boolean
值
console.log(set.has('1'))//true
console.log(set.has('2'))//false
(4)clear()
用于清除所有值
set.clear()
console.log(set)//set(0){size:0}
(5)for...of
由于Set
只有键值没有键名,也可以说键和值是同一个(键、值相同,可以省略) ,所keys
和values
返回值相同,如下:
let set = new Set();
set.add('1').add('2').add('3')
console.log('遍历键')
for(let i of set.keys()){
console.log(i)
}
console.log('遍历值')
for(let j of set.values()){
console.log(j)
}
console.log('打印键值对')
for(let q of set.entries()){
console.log(q)
}
2.set案例
// 数组去重
let arr = [1,3,5,2,3,6,3,2];
let set = new Set(arr);
let result = [...set]
console.log('去重后数组:',result)
// 求两个数组的交集
let arr1 = [1,2,3,4,5,6]
let arr2 = [2,3,4,7]
let set1 = new Set(arr2)
let result1 = [... new Set(arr1)].filter(item=>set.has(item))
console.log('A∩B:',result1);
// 求两个数组的并集
let result2 = [...new Set([...arr1,...arr2])]
console.log('A∪B:',result2)
// 求两个数组的差集
let set2 = new Set(arr1);
let set3 = new Set(arr2)
let result3 = [...set2].filter(item=>!set3.has(item))
console.log('A-B:',result3)
二、Map()集合
ES6提供了Map数据结构。它类似于对象,也是键值对的集合,但是“键”的范围不限于字符串,各种类型的值(包括对象)都可以当作键。也就是说,Object结构提供了“字符串—值”的对应,Map结构提供了“值—值”的对应,是一种更完善的Hash结构实现。
ES6中的Map类型是一种储存着许多键值对的有序列表,其中的键名和对应的值支持所有的数据类型。键名的等价性判断是通过调用Object.is()方法实现的,所以数字5与字符串"5"会被判定为两种类型,可以分别作为独立的两个键出现在程序中,这一点与对象不一样,因为对象的属性名总会被强制转换成字符串类型。
1、操作方法
方法 | 说明 |
set() | 给 |
get() | 获取某个 |
has() | 检测是否存在某个 |
delete() | 删除某个 |
clear() | 清除所有的值,返回 |
let map = new Map();
// set()用法
map.set('name','张三').set('age',20);
console.log(map)//Map(2) { 'name' => '张三', 'age' => 20 }
// get()用法
console.log(map.get('name')) // 张三
// has()用法
console.log(map.has('age'))//true
console.log(map.has('birday'))//false
// delete()用法
console.log(map.delete('age'))//true
console.log(map)//Map(1) { 'name' => '张三' }
// clear()用法
console.log(map.clear())//undefined
console.log(map)//Map(0) {}
2.Map()的遍历
(1)for...of实现遍历
Map
的遍历顺序就是插入顺序
console.log('遍历键:')
for(let key of map.keys()){
console.log(key)
}
console.log('遍历值:')
for(let values of map.values()){
console.log(values)
}
console.log('遍历键值对:')
for(let [key,value] of map){
console.log(key,value)
}
(2)forEach()遍历
const map = new Map([[1, 'one'],[2, 'two'],[3, 'three']]);
console.log(map);
map.forEach((value,key,map)=>{
console.log(value,key,map);
})
我们还可以结合数组的map
方法、filter
方法,可以实现 Map
的遍历和过滤,如下
const map0 = new Map().set(1,'wh').set(2,'rc').set(3,'xl');
const map1 = new Map([...map0].filter(([k,v])=>k<3));
console.log(map1);