Set数据结构
es6新增了一种全新的数据结构,类似于数组,但其中的元素不允许重复,也就是每个元素在其中都是唯一的,我们可以称之为:集合 即Set
Set中认为两个NaN是相等的
一般我们可以使用Set进行数组的去重
集合中新增元素
// 方式一
const set = new Set()
set.add(1).add(5).add(2).add(4).add(5).add(3).add(2)
console.log(set) // Set { 1, 5, 2, 4, 3 }
// 方式二
const set = new Set([1, 5, 2, 4, 5, 3, 2])
console.log(set) // Set { 1, 5, 2, 4, 3 }
我们可以看到 set中的值都是唯一的
集合的遍历
set.forEach(item => {
console.log(item)
})
当然也可以使用 for of
获取集合长度等自有方法
// 1.获取集合长度
console.log(set.size)
// 2.判断集合当中是否存在某个值
console.log(set.has(6)) // false
// 3.删除集合中某个指定值,方法会返回是否删除成功
console.log(set.delete(3)) // true
// 4.清空集合
set.clear()
console.log(set) // Set {}
通过Set 进行数组的去重
let lists = [2, 1, 3, 2, 1, 5, 4, 2, 4, NaN, NaN, null, null, undefined, undefined]
// 方式一
let list = Array.from(new Set(lists))
console.log(list) // [ 2, 1, 3, 5, 4, NaN, null, undefined ]
// 方式二
let list = [new Set(lists)]
console.log(list) // [ 2, 1, 3, 5, 4, NaN, null, undefined ]
Map数据结构
Map 和对象很像,它们本质上都是键值对集合。map的key可以是任意类型
map新增元素
// 方式一
const map = new Map()
map.set({name: 'xxx'}, 1).set(true, 2).set('tom', 3).set([1,2], 4).set(2, 5).set(null, 6).set(undefined, 7)
console.log(map) //{ { name: 'xxx' } => 1, true => 2, 'tom' => 3, [ 1, 2 ] => 4, 2 => 5, null => 6, undefined => 7 }
// 方式二
const map = new Map([[{name: 'xxx'}, 1], [true, 2], ['tom', 3], [[1,2], 4], [2, 5], [null, 6], [undefined, 7]])
console.log(map) //{ { name: 'xxx' } => 1, true => 2, 'tom' => 3, [ 1, 2 ] => 4, 2 => 5, null => 6, undefined => 7 }
map其他自有方法
// 1.根据键获取对应值
map.get('tom')
// 2.判断某键是否存在
map.has('tom')
// 3.删除某个键
map.delete('tom')
// 4.清空所有键
map.clear()
// 5.遍历所有键值,需要注意的是首个参数是值,第二参数是键
map.forEach((value, key) => {
console.log(value, key)
})