Java教程

ES6-set和map

本文主要是介绍ES6-set和map,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

map和set

(1): set类似于数组,属性值是独一无二的

set设置

let set = new Set();
set.add(1);
set.add(2);
set.add(3).add(4) // 链式写法
console.log("set",set); // set Set(3) { 1, 2, 3 }

let set1 = new Set([1,2,3,4])

set三个迭代器和一个遍历的方法

set.values
set.keys
set.entries
set.forEach
for(let v of set) {
  console.log("值为11:",v); // 123
}
for(let v of set.values()) {
  console.log("值为22:",v); // 123
}
for(let v of set.keys()) {
  console.log("值为33",v); // 123
}

set的属性 size

let size = set.size

set的删除 delete

set.delete(1) 

set判断是否有某个值has

console.log(set.has(1)); // false

set 清除所有的值

set.clear() // 清除所有的值

set 数组去重

let arr1 = [1,1,2,2,3,4,5,6]
let uniqueArr = Array.from(new Set(arr1))
<!--let uniqueArr = [...new Set(arr1)]-->
console.log("uniqueArr",uniqueArr);

weakSet和 set区别

首先,WeakSet 的成员只能是对象,而不能是其他类型的值。
其次,WeakSet 中的对象都是弱引用,即垃圾回收机制不考虑 WeakSet 对该对象的引用,也就是说,如果其他对象都不再引用该对象,那么垃圾回收机制会自动回收该对象所占用的内存,不考虑该对象还存在于 WeakSet 之中。

注意Array.from直接转换对象为数组

 let obj = {id:1,name:"张三"}
 let arr1 = Array.from(obj) // 转换的是空数组
 let arr2 = Array.of(obj) // 转换为数组[{id:1,name:"张三"}]
 
 

注意Array.of不可以转换 new Set()这样的数组

 let set = new Set([1,2,3])
 let arr3 = Array.of(set) 
 console.log(arr3) // [Set(4)]
 

(2): map类似于对象,属性名是独一无二的

// Map是一对的,分为key 和 value
// 通过key 去获取value
// 有对象,还要map干嘛
// 区别 Map具有size属性,获取所有的元素数量
// Map可以迭代的,对于遍历会更加方便
// 针对于删除或者添加元素,不建议使用对象而是Map

map的设置

let map = new Map()
map.set(1,"a");
map.set("2","c");
map.set("3","d").set("4","e") // 链式写法

console.log("map",map); // { 1 => 'a', '2' => 'c', '3' => 'd', '4' => 'e' }

let map1 = new Map([["1","a"],["2","c"],["3","d"]])
console.log("map1",map1); //  { '1' => 'a', '2' => 'c', '3' => 'd' }

let arr1 = Array.from(map1) // 通过Array.from转换为二维数组
console.log("arr1",arr1); // [ [ '1', 'a' ], [ '2', 'c' ], [ '3', 'd' ] ]

map的属性 size

map.size // 获取长度

map的删除

map1.delete("1") // 删除键名
console.log("object",map1.delete("1"));

has判断是否有某值

map1.has("1") // false

map获取值

console.log(map1.get("2")); // c

clear() 删除所有

map.clear()

map的三种可迭代的遍历器和一个遍历的方法

map.keys 键
map.values 值
map.entries 全部的值(键值对)
map.forEach()

weakMap
WeakMap只接受对象做为键名(null除外),不接受其它的值做为键名
WeakMap的键名所指向的对象,不计入垃圾回收机制

map实现数组去重

let arr = [1,1,2,2,3,4,5,6]
function uniqueArr(arr) {
  let map = new Map();
  let arr1 = []
  for(let i in arr) {
    if(!map.has(arr[i])) {
      map.set(arr[i],true)
      arr1.push(arr[i])
    }
  }
  return arr1
}
uniqueArr(arr) // [1, 2, 3, 4, 5, 6]
这篇关于ES6-set和map的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!