说一说 Set 和 Map
说一说 Set 和 Map
发布时间:2025-02-21 08:06:54
说一说 Set 和 Map
Set 对象是值的集合,Set 中的元素只会出现一次,即 Set 中的元素是唯一的。
// 创建一个 Set 对象
const set = new Set()
// 向 Set 对象中添加一个值
set.add(1)
// 判断 Set 对象中是否存在某个值
set.has(1)
// 获取 Set 对象的长度
set.size
// 删除 Set 对象中的某个值
set.delete(1)
// 清除 Set 对象中的所有值
set.clear()
Map 对象是键值对的集合。
// 创建一个 Map 对象
const map = new Map()
// 向 Map 对象中插入一个键值对
map.set('a', 1)
// 获取 Map 对象中键对应的值
map.get('a')
// 判断 Map 对象中是否存在某个键值对
map.has('a')
// 获取 Map 对象键值对的个数
map.size
// 删除 Map 对象中的某个键值对
map.delete('a')
// 移除 Map 对象中所有的键值对。
map.clear()