码迷,mamicode.com
首页 > 其他好文 > 详细

ES6(九)set、map数据结构

时间:2019-09-09 22:38:10      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:return   weak   结构   color   删除   接收   obj   foreach   set   

Set 元素不会重复

let list = new Set()
list.add(5)
list.add(7)
console.log(list)
// 长度
console.log(list.size)


let arr = [1, 2, 3, 4, 5]
let list = new Set(arr)
console.log(list)


去重

let arr = [1, 2, 3, 4, 2, 3, 4, 3, 4]
let list = new Set(arr)
console.log(list)

增删查改

let arr = [‘add‘, ‘delete‘, ‘clear‘, ‘has‘]
let list = new Set(arr)
// 是否在数组里
console.log(list.has(‘add‘))
// 删除
list.delete(‘add‘)
console.log(list)
// 清空
list.clear()
console.log(list)


let arr = [33, 11, 35, 78, 99]
let list = new Set(arr)
for (let key of list.keys()) {
  console.log(key)
}
for (let value of list.values()) {
  console.log(value)
}
for (let value of list) {
  console.log(value)
}
for (let [key, value] of list.entries()) {
  console.log(key, value)
}
list.forEach(item => {
  return console.log(item)
})

和Set增删查改循环一样

// 区别:weakList只能接收对象
// 只具有 add has delete方法
let weakList = new WeakSet()

let obj = {
  name: ‘ronle‘
}
weakList.add(obj)
console.log(weakList)
console.log(weakList.has(obj))


Map(增加值是用set方法,而不是add)

let map = new Map()
let key = [‘123‘]

map.set(key, ‘456‘)
console.log(map)
// 获取对应key的值  456
console.log(map.get(key))


let map = new Map([[‘a‘, ‘123‘], [‘b‘, 456]])
map.set(‘c‘, ‘789‘)
for (let [key, value] of map.entries()) {
  console.log(key, value)
}
console.log(map.size)
console.log(map.has(‘b‘))
console.log(map.delete(‘a‘))
console.log(map.clear())


let weakMap = new WeakMap()
let obj = {}
// 只具有set get has delete方法
weakMap.set(obj, 123)
console.log(weakMap)
console.log(weakMap.get(obj))

 

ES6(九)set、map数据结构

标签:return   weak   结构   color   删除   接收   obj   foreach   set   

原文地址:https://www.cnblogs.com/ronle/p/11494602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!