Set数据结构-《ES6 入门教程》阮一峰学习笔记

166 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第9天,点击查看活动详情

前言

ES6提供了新的叫做Set的数据结构。在我的理解里,Set数据结构因为其键值唯一性所以很多时候都是用来排重。下面我们便来说说这种数据结构。

Set数据结构

什么是Set

Set是一种类似于数组的结构,键值都是唯一值。定义的方式为const a=new Set()

const a=new Set([1,2,3,4,5])
console.log(a);  //Set { 1, 2, 3, 4, 5 }

Set实例的属性

  • Set.prototype.constructor:构造函数,默认就是Set函数通过new Set()调用。
  • Set.prototype.size:返回Set实例的成员总数。

Set实例的方法

Set 实例的方法分为两大类:操作方法(用于操作数据)和遍历方法。下面先介绍四个操作方法。

Set实例的操作方法

  • Set.prototype.add(value):添加某个值,返回 Set 结构本身。
  • Set.prototype.delete(value):删除某个值,返回一个布尔值,表示删除是否成功。
  • Set.prototype.has(value):返回一个布尔值,表示该值是否为Set的成员。
  • Set.prototype.clear():清除所有成员,没有返回值。

Set实例的遍历方法

Set数据结构也有与数组、对象类似的遍历方法

  • Set.prototype.keys():返回键名的遍历器
  • Set.prototype.values():返回键值的遍历器
  • Set.prototype.entries():返回键值对的遍历器
  • Set.prototype.forEach():使用回调函数遍历每个成员

Set数据结构的使用

Set数据结构的操作方法

const b=new Set(["a","b","c","d","e"])
console.log(b.size);  //5  返回数组长度为length
console.log(b.add("f")); //Set { 'a', 'b', 'c', 'd', 'e', 'f' }
console.log(b.has("f")); //true
console.log(b.delete("f")); //true
console.log(b.clear()); //undefined

Set数据结构的遍历方法

由于 Set 结构没有键名,只有键值(或者说键名和键值是同一个值),所以keys方法和values方法的行为完全一致。因为返回的是遍历器对象,所以可用for...of遍历

const b=new Set(["a","b","c","d","e"])
console.log(b.keys());//[Set Iterator] { 'a', 'b', 'c', 'd', 'e' }
console.log(b.values());//[Set Iterator] { 'a', 'b', 'c', 'd', 'e' }
console.log(b.entries());//[Set Entries] {[ 'a', 'a' ],[ 'b', 'b' ],[ 'c', 'c' ],[ 'd', 'd' ],[ 'e', 'e' ]}
b.forEach((value,key)=>{
  console.log(key+':'+value);
})//a:a
    b:b
    c:c
    d:d
    e:e

数组排重

const a=[1,2,3,3,4,5,4,6,7,7,6,8]
console.log([...new Set(a)]); //[1,2,3,4,5,6,7,8]

总结

总之,如果不打算修改成员时,Set或许是很好的选择。其他除了数组排重还是用数组更好一些。毕竟,我们也不希望后端传来的数据再给他改为Set╰(°▽°)╯。