Basic usage of Set type in ES6

Before ES6, there were two main structures for storing data: arrays and objects .
In ES6, two other data structures (the way of storing data) are added: Set, Map , and their other forms WeakSet and WeakMap.

Basic use of Set

Set is a new data structure that can be used to save data, similar to an array, but the difference from an array is that elements cannot be repeated. To create a Set, you need to pass the Set constructor (there is no literal way to create it).

1) Create a Set structure

// 1.创建Set结构
const set = new Set()
// 想要向Set类型中添加数据使用add()
set.add(10)
set.add(20)
set.add(40)

// Set中元素不能重复,如果重复添加同一个数值,最终只存在一个
set.add(10)
console.log(set);

insert image description here
2) Pay special attention when adding objects to the Set structure

// 1.创建Set结构
const set = new Set()
// 想要向Set类型中添加数据使用add()
set.add(10)
set.add(20)
set.add(40)

// 2.添加对象时特别注意:
// 如果重复向Set类型的元素中添加多个对象,会显示这两个对象都在内存中,因为这是两个不同的对象,其中保存的是不同的地址
set.add({
    
    })
set.add({
    
    })

// 但是使用下面这种方式创建对象
const obj = {
    
    }
// 这种方式向set中添加对象,添加的是同一个对象
set.add(obj)
set.add(obj)

console.log(set);

insert image description here
3) Application scenario - deduplication of arrays

// 3.对数组去重(去除重复的元素)
const arr = [33, 10, 25, 30, 33, 26]

const arrSet = new Set(arr)   // Set()括号中传入可迭代对象
const newArr1= Array.from(arrSet)    // arrSet实际上还是Set类型,将它变换为数组类型
const newArr = [...arrSet]    // Set类型的也支持使用展开运算符

console.log(newArr,newArr1);

insert image description here

Guess you like

Origin blog.csdn.net/qq_44482048/article/details/129151987