Map是类似Object的一种键值对集合,区别在于Map的键不仅限于是字符串,其他各种类型的值包括对象都可以成为Map的键
//示例1
const map = new Map()
map.set(1, 'one')
map.set(2, 'two')
map.set(3, 'three')
console.log(map) // {1 => "one", 2 => "two", 3 => "three"}
map.get(1) // 'one'
map.has(2) //true
// 使用for...of来遍历 可获得key集合 和 value集合
for(const item of map.keys()){
console.log(item) //1 2 3
}
for(const item of map.values()){
console.log(item) //'one' 'two' 'three'
}
for(const item of map.entries()){
console.log(item)// [1, 'one'] [2, 'two'] [3, 'three']
}
// size: 返回 map对象中所包含的键值对个数
// set(key, val) 向map中添加新元素
// get(key) 通过键值查找特定的值
// has(key) 判断map中是否存在key,有返回true, 没有返回false
// delet(key) 通过键值从map中移除对应的数据
// clear() 将map中所有元素删除
// keys() 返回键名的遍历器
// values() 返回键值的遍历器
// entries() 返回键值对遍历器
// forEach() 遍历每个成员
//示例2
var map = new Map();
var obj = { name: 'tom', age: 14 };
map.set(obj, 'jack');
map.get(obj); // jack
map.has(obj); // true
map.delete(obj) ;// true
map.has(obj); // false
Set 是类似于数组的一种数据结构,且成员的值都是唯一的。
const numSet = new Set()
numSet.add(1)
//console.log(numSet)//{1}
numSet.add(2) //{1,2}
numSet.add(1) //{1,2,3} 重复的值不会添加进去
numSet.add(7) //{1,2,3,7}
numSet.delete(1) //true 被删掉返回true
//console.log(numSet) //{2,7}
numSet.has(2) //true
numSet.has(1) //false
//console.log('setSize:',numSet.size) //2 长度
numSet.forEach(el=>{ console.log(el) }) //2 7
const set = new Set([1,2,3]);
for(const item of set.keys()){
console.log(item) // 1 2 3
}
for(const item of set.values()){
console.log(item) // 1 2 3
}
for(const item of set.entries()){
console.log(item)// 键值一样 [1, 1] [2, 2] [3, 3]
}