search
HomeWeb Front-endFront-end Q&AWhat is the use of es6 set?

What is the use of es6 set?

Oct 24, 2022 pm 05:55 PM
javascriptes6

Set is a data structure used to store ordered data. The elements in Set are unique and are not allowed to store the same elements; Set() can accept an iterable object as a parameter, but will Identical content in this iterable object is removed, so it can be used to remove duplicate elements and prevent "Array.from(new Set(arr))" or "[...new Set(arr)]".

What is the use of es6 set?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

1. Basic usage

Set is a new data structure provided by ES6, it is the same as an array It is used to store ordered data, but it does not have random access capabilities. That is to say, it cannot obtain a specific element through indexing like an array. In addition, the most important thing is that the elements in Set are unique and the same elements are not allowed to be stored!

Set is a constructor used to instantiate an instance:

let set = new Set()
set.add(1)//往set集合中添加元素1

In addition, Set() can accept a The iterable object is used as a parameter as the instance initialization data, but the same content in the iterable object will be removed. However, this is also a method of array deduplication.

let set = new Set([1,2,2,1,4,3,5])
console.log(set)//Set(5) {1, 2, 4, 3, 5}

The uniqueness of elements can be used to deduplicate arrays:

//方法一:
Array.from(new Set(arr)) //arr是待去重的数组

//方法二:
[...new Set(arr)]

How cool. Similarly, this feature can also be used to deduplicate the same characters in a string. .

[...new Set(str)].join('')

However, the above are all achieved through the uniqueness of Set type elements, so how does Set internally determine whether an element is unique? It uses an algorithm internally Same-value-zero equality, which is roughly the same as the equality operator. The difference is that this algorithm considers NaN equal to NaN.

2. Instance properties and methods

Instance properties

On Set.prototype, An attribute size is defined to represent the number of elements.

let set = new Set([1,2,2,1,4,3,5])
console.log(set.size)//5

Instance methods

#Set Instance methods can be divided into two categories: operation methods and traversal methods.

1. Operation method

  • Set.prototype.add(value) —— Add a value to Set At the end of , returns Set itself.
  • Set.prototype.delete(value) —— Delete a certain value and return a Boolean value to indicate whether the deletion was successful.
  • Set.prototype.has(value) - Returns a Boolean value indicating whether the value is an element of Set.
  • Set.prototype.clear() —— Clear all members, no return value.

It is worth mentioning that the return of the add() method is Set itself, so you should be able to think of chain calls:

let set = new Set()
set.add(1).add(2).add(3)

2. Traversal method

  • ##Set.prototype.keys() —— Returns the traverser of key names
  • Set.prototype.values() —— Returns a traverser of key-value pairs
  • Set.prototype.entries() —— Returns a traverser of key-value pairs
  • Set.prototype.forEach() —— Use the callback function to traverse the elements
Since the

Set structure has no key names, only key values ​​( In other words, the key name and key value are the same value), so the keys method behaves exactly the same as the values method.

3. WeakSet

##WeakSet

is an upgraded version of Set, there are two main ones Difference:

    WeakSet
  • can only store reference types, not basic type data. The reference types in
  • WeakSet
  • are all weak references.
  • First of all, the first point is easy to understand, that is, basic types of data cannot be stored:
const ws = new WeakSet()
ws.add(1)//报错,Invalid value used in weak set

Then the second point, the objects in

WeakSet

are Weak reference. This means that the garbage collection mechanism will not consider WeakSet's reference to the object. Once the external reference count reaches 0, it will wait to be processed by the garbage collection mechanism. Therefore, WeakSet is suitable for temporarily storing a group of objects. Due to this feature, members in

WeakSet

are not suitable for reference because it is likely to be cleaned up at any time. However, ES6 stipulates that it is not traversable . The method in

WeakSet

is basically the same as the Set mentioned above, but it does not have the size attribute and no traverser method. 【Related recommendations:

javascript video tutorial

, programming video

The above is the detailed content of What is the use of es6 set?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Size of React's Ecosystem: Navigating a Complex LandscapeThe Size of React's Ecosystem: Navigating a Complex LandscapeApr 28, 2025 am 12:21 AM

TonavigateReact'scomplexecosystemeffectively,understandthetoolsandlibraries,recognizetheirstrengthsandweaknesses,andintegratethemtoenhancedevelopment.StartwithcoreReactconceptsanduseState,thengraduallyintroducemorecomplexsolutionslikeReduxorMobXasnee

How React Uses Keys to Identify List Items EfficientlyHow React Uses Keys to Identify List Items EfficientlyApr 28, 2025 am 12:20 AM

Reactuseskeystoefficientlyidentifylistitemsbyprovidingastableidentitytoeachelement.1)KeysallowReacttotrackchangesinlistswithoutre-renderingtheentirelist.2)Chooseuniqueandstablekeys,avoidingarrayindices.3)Correctkeyusagesignificantlyimprovesperformanc

Debugging Key-Related Issues in React: Identifying and Resolving ProblemsDebugging Key-Related Issues in React: Identifying and Resolving ProblemsApr 28, 2025 am 12:17 AM

KeysinReactarecrucialforoptimizingtherenderingprocessandmanagingdynamiclistseffectively.Tospotandfixkey-relatedissues:1)Adduniquekeystolistitemstoavoidwarningsandperformanceissues,2)Useuniqueidentifiersfromdatainsteadofindicesforstablekeys,3)Ensureke

React's One-Way Data Binding: Ensuring Predictable Data FlowReact's One-Way Data Binding: Ensuring Predictable Data FlowApr 28, 2025 am 12:05 AM

React's one-way data binding ensures that data flows from the parent component to the child component. 1) The data flows to a single, and the changes in the state of the parent component can be passed to the child component, but the child component cannot directly affect the state of the parent component. 2) This method improves the predictability of data flows and simplifies debugging and testing. 3) By using controlled components and context, user interaction and inter-component communication can be handled while maintaining a one-way data stream.

Best Practices for Choosing and Managing Keys in React ComponentsBest Practices for Choosing and Managing Keys in React ComponentsApr 28, 2025 am 12:01 AM

KeysinReactarecrucialforefficientDOMupdatesandreconciliation.1)Choosestable,unique,andmeaningfulkeys,likeitemIDs.2)Fornestedlists,useuniquekeysateachlevel.3)Avoidusingarrayindicesorgeneratingkeysdynamicallytopreventperformanceissues.

Optimizing Performance with useState() in React ApplicationsOptimizing Performance with useState() in React ApplicationsApr 27, 2025 am 12:22 AM

useState()iscrucialforoptimizingReactappperformanceduetoitsimpactonre-rendersandupdates.Tooptimize:1)UseuseCallbacktomemoizefunctionsandpreventunnecessaryre-renders.2)EmployuseMemoforcachingexpensivecomputations.3)Breakstateintosmallervariablesformor

Sharing State Between Components Using Context and useState()Sharing State Between Components Using Context and useState()Apr 27, 2025 am 12:19 AM

Use Context and useState to share states because they simplify state management in large React applications. 1) Reduce propdrilling, 2) The code is clearer, 3) It is easier to manage global state. However, pay attention to performance overhead and debugging complexity. The rational use of Context and optimization technology can improve the efficiency and maintainability of the application.

The Impact of Incorrect Keys on React's Virtual DOM UpdatesThe Impact of Incorrect Keys on React's Virtual DOM UpdatesApr 27, 2025 am 12:19 AM

Using incorrect keys can cause performance issues and unexpected behavior in React applications. 1) The key is a unique identifier of the list item, helping React update the virtual DOM efficiently. 2) Using the same or non-unique key will cause list items to be reordered and component states to be lost. 3) Using stable and unique identifiers as keys can optimize performance and avoid full re-rendering. 4) Use tools such as ESLint to verify the correctness of the key. Proper use of keys ensures efficient and reliable React applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.