map和set

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]
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值