ES6(九)set、map数据结构

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))

应用

      // 长度为7的数组,填充为0
      let arr = new Array(7).fill(0);
      console.log(arr);

      // charAt 方法返回正确的字符。
      console.log('abc'.charAt(0) === 'a');

      // 连接数组
      let result = [];
      let arr2 = [1, 2, 3];
      let arr3 = [4, 5, 6];
      result = [].concat(arr2, arr3);
      console.log(result)

      // map
      let myMap = new Map();
      myMap.set('obj1', {
        name: 'ronle',
        age: 6
      }).set('obj2', {
        name: 'kaka',
        age: 9
      });
      let exist = myMap.has('obj');
      console.log(exist);
      console.log(myMap);

      // set
      let mySet = new Set();
      for (let i = 0; i < 12; i++) {
        mySet.add(('' + i).padStart(2, '0'))
      }
      console.log(mySet)

 

posted @ 2019-09-09 22:09  ronle  阅读(213)  评论(0编辑  收藏  举报