Map详解
- map字典是以[键,值]的形式存储;键各不相空,相同的键,后面的键值会覆盖前面的键值
- map.size返回Map结构的成员总数。
- map.set(key, value)是新增
- map.get(key)是查询
- map.has(key)方法返回一个布尔值,表示某个键是否在当前 Map 对象之中
- map.delete(key)方法删除某个键,返回true。如果删除失败,返回false
- map.clear()方法清除所有成员,没有返回值。
查询,删除,查键,对象和数组无法通过直接书写来查询,需要for循环遍历出键才可以,推测应该是存储地址问题
const map = new Map([['c', 8], ['c', 9]])
map.set('a', 1)
map.set(5, 3)
map.set({ off: 1 }, 2)
map.set([1, 2], 3)
map.set(undefined, undefined)
map.set(NaN, NaN)
// 相同的键c,后面的键值覆盖了前面的键值
console.log(map,map.size) // Map(7){c=>9,a=>1,5=>3,{off:1}=>2,[1,2]=>3,undefined=>undefined,NaN=>NaN} 7
// 如果键为对象、数组、undefined都不能查询所对应的值,需要for循环进行查询
console.log(map.get('a'),map.get(5), map.get([1, 2]), map.get("[1, 2]"),map.get({off:1}),map.get("{off:1}"),map.get(undefined),map.get(NaN)) // 1 3 undefined undefined undefined undefined undefined NaN
// 如果键为对象、数组、undefined都不能确定其对应的键是否是在map字典中
console.log(map.has([1, 2]), map.has(NaN), map.has('a'), map.has({ off: 1 })) // false true true false
// 如果键为对象、数组、undefined都不能删除其对应的键值对
console.log(map.delete('a'), map.delete([1, 2])) // true false
for (let item of map) {
console.log(11,item)
console.log(item[0], map.get(item[0]))
}
set详解
- set()是es6新增的数据结构,类似于数组,但它的一大特性就是所有元素都是唯一的,没有重复的值,我们一般称为集合,Set本身是一个构造函数,用来生成 Set 数据结构。
- set.add(val)添加某个值,返回 Set 结构本身,当添加实例中已经存在的元素,set不会进行处理添加
- set.delete(val)删除某个值,返回一个布尔值,表示删除是否成功
- set.has(val)返回一个布尔值,判断该值是否为Set的成员
- set.clear()清除所有成员,没有返回值
// 数组去重
const arr = [2, 5, 6, 8, 7, 2, 4, 21, 5, 5, 6, 2]
const setArr = new Set(arr)
console.log(setArr) // set{2, 5, 6, 8, 7, 4, 21}
// es6 ...解构
const unique1 = [...setArr]
console.log(unique1) // [2, 5, 6, 8, 7, 4, 21]
// Array.from()解析类数组为数组
const unique2 = Array.from(setArr)
console.log(unique2) // [2, 5, 6, 8, 7, 4, 21]
// 字符串去重
const str = '3226584233256'
const setStr = new Set(str)
console.log(setStr) // set{"3","2","6","5","8","4"}
const uniqueStr = [...setStr].join()
console.log(uniqueStr) // 3,2,6,5,8,4
// 并集、交集、差集
const a = new Set([1, 2, 3])
const b = new Set([2, 3, 4])
// 并集
const union = new Set([...a, ...b])
console.log(union) // set{1, 2, 3, 4}
// 交集
const intersect = new Set([...a].filter(x => b.has(x)))
console.log(intersect) // Set{2, 3}
// 差集(a相对于b的差集)
const difference = new Set([...a].filter(x => !b.has(x)))
console.log(difference) // Set{1}