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; }; }
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. <pre class="brush:php;toolbar:false">union(set) {
if (!this._isValid(set)) return new SetHelper();
return new SetHelper([...this, ...set]);
}</pre>
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. <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>
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. <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>
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


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

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

Hot Article

Hot Tools

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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software