What is Set in JavaScript? When to use? how to use?
Javascript needs to use Set in some cases. The following article will take you to understand Set, introduce what Set is, when to use Set, and the data operations of Set (intersection, difference set, intersection, symmetric difference set).
In many cases, you need to compare multiple lists to obtain whether they have intersection or difference, etc. There is a data type in Javascript that can achieve this very well. Demand, that is Set
.
Set
The object is like an array, but contains only unique items. Set
The object is a collection of values, and its elements can be iterated in the order of insertion. The elements in Set
will only appear once, that is, the elements in Set
are unique.
The code address involved in the article: https://codepen.io/quintiontang/pen/rNmNbbY
What is Set
Set
The object is a collection of values. Its elements can be iterated in the order of insertion. The elements will only appear once, that is, Set
is not in a specific order. A stored collection of unique values. Unlike other collection types such as stacks, queues, and arrays, Sets can be used for list comparisons and for detecting the presence of an item in a set.
Set
is an abstract data type that is defined by its behavior, similar to stack and queue data structures. Due to the characteristics of key-key
, this is similar to Map
.
Javascript Set
Set
in Javascript is very basic and simple, it doesn’t provide as much as other languages General set operation functions. It uses a unique algorithm (not based on strict equality ===
) to detect whether elements are identical.
This means that storing undefined
, null
and NaN
in the collection will only be stored once, even if it is NaN != = NaN
, which is usually applied to the storage of object types.
const setTest = new Set([0, -0, Infinity,null, undefined, null, NaN, NaN, Infinity,null]); console.log(setTest); // Set { 0, Infinity, null, undefined, NaN }
The following conclusions can be drawn from the above execution results:
- Although
NaN
andNaN
are not equal, but inSet
There will only be one undefined
in the set andInfinity
There will only be one# in the
Set set
mozilla website.
When to use Set
When you need to compare a specific list and determine whether it is equal, you can use Set , let’s describe the applicable occasions, mainly the set operations in the data:
- Get the union of two sets
- union
- difference
- intersection
- intersectionDifference
- isSubset
- isSuperset
Set based on these three occasions.
Set Operations
In mathematics, whenever we talk about sets, there are some operations that can be performed, in fact, Set is the computer implementation of mathematical finite sets.
Set operation in the code, the sample code will extend Javascript
Set to inherit its properties and methods, and add other methods to it.
For the sample code, only a simple method is used to check whether it is a valid collection that is not empty.class SetHelper extends Set { /** * 验证集合是否为有效集合 * @param {*} set * @returns */ _isValid = (set) => { return set && set instanceof Set && set.size > 0; }; }Copy after login
Unionunion
The operation will merge multiple Set
Object and return the combined result. The implementation merges the current set and the given set into an array and creates it, thus returning a new set. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">union(set) {
if (!this._isValid(set)) return new SetHelper();
return new SetHelper([...this, ...set]);
}</pre><div class="contentsignin">Copy after login</div></div>
difference
The operation will return a new set that is only contained in one set Elements that are in and not in another set, that is, the mathematical concept of difference set. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">difference(set) {
if (!this._isValid(set)) return new SetHelper();
const differenceSet = new SetHelper();
this.forEach((item) => {
!set.has(item) && differenceSet.add(item);
});
return differenceSet;
}</pre><div class="contentsignin">Copy after login</div></div>
intersection
The operation returns a new collection containing only elements common to both collections. The implementation will iterate over the smaller collection (avoiding unnecessary checks) and check if each item exists in the larger collection and add it to the intersection, which will be returned after the traversal is complete. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>intersection(set) {
const intersectionSet = new SetHelper();
if (!this._isValid(set)) return intersectionSet;
const [smallerSet, biggerSet] =
set.size <= this.size ? [set, this] : [this, set];
smallerSet.forEach((item) => {
biggerSet.has(item) && intersectionSet.add(item);
});
return intersectionSet;
}</pre><div class="contentsignin">Copy after login</div></div>
intersectionDifference##intersectionDifference
intersectionDifference(set) { if (!this._isValid(set)) return new SetHelper(); return new SetHelper([ ...this.difference(set), ...set.difference(this), ]); }
subset subset<p><code>isSubset
操作将判断两个集合是否为子集关系(当一个集合的所有项都包含在另一个集合中时)。实现上首先检查两个集合的大小,如果一个集合更大,则它不能是另一个集合的子集,然后对于每个项目,它检查它是否存在于另一个中。
isSubset(set) { if (!this._isValidSet(set)) return false; return ( this.size <= set.size && [...this].every((item) => set.has(item)) ); }
超集 superset
isSuperset
操作将判断两个集合是否为超集关系。超集是子集的反操作。当一个集合包含另一个较小或相等大小的集合的所有项目时,它就是一个超集。
isSuperset(set) { if (!this._isValidSet(set)) return false; return ( this.size >= set.size && [...set].every((item) => this.has(item)) ); }
静态 Set
静态Set
是一个始终包含它初始化元素的集合,不能添加、删除、清除元素。Javascript Set
不是静态的,它总能在创建后可以公开修改该集合的方法,如 add
、delete
,为避免集合被修改,可以创建一个新的 Set
,将其修改方法重置 。
class StaticSet extends SetHelper { constructor(items) { super(items); this.add = undefined; this.delete = undefined; this.clear = undefined; } }
使用
现在就可以使用上面定义的方法操作两个 Set
,如下:
const setA = new StaticSet(new Set([1, 2, 3, 4])); const setB = new StaticSet(new Set([3, 4, 5, 6])); console.log([...setA.union(setB)]); // [ 1, 2, 3, 4, 5, 6 ] console.log([...setA.difference(setB)]); // [ 1, 2 ] console.log([...setA.intersection(setB)]); // [ 3, 4 ] console.log([...setB.intersectionDifference(setA)]); // [ 5, 6, 1, 2 ]
总结
Set
不限于上面这些操作,之前有介绍过可以用来合并数组去重,由于 Set
和 Array
相互转换很简单,因此可以用到 Array
的场合可以优先考虑一下 Set
,因为在内存使用上, Set
比 Array
占用更少。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of What is Set in JavaScript? When to use? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
