Table of Contents
What is Set
Javascript Set
When to use Set
Set Operations
静态 Set
使用
总结
Home Web Front-end JS Tutorial What is Set in JavaScript? When to use? how to use?

What is Set in JavaScript? When to use? how to use?

Jul 16, 2021 pm 07:19 PM
javascript set

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).

What is Set in JavaScript? When to use? how to use?

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.

SetThe object is like an array, but contains only unique items. SetThe 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 }
Copy after login

The following conclusions can be drawn from the above execution results:

  • Although NaN and NaN are not equal, but in Set There will only be one
  • undefined in the set and Infinity There will only be one # in the Set
  • set
##The use of basic Set will not be introduced in this article. You can refer to the

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
  • Get the two sets The difference set
  • difference
  • Get the intersection of two sets
  • intersection
  • Get the symmetric difference set of two sets
  • intersectionDifference
  • Judge whether two sets are subsets
  • isSubset
  • Judge whether two sets are supersets
  • isSuperset
The following will introduce the related operations of

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.

In order to better demonstrate the

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

##union

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 set

difference

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) =&gt; { !set.has(item) &amp;&amp; differenceSet.add(item); }); return differenceSet; }</pre><div class="contentsignin">Copy after login</div></div>

Intersection

intersection

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 &lt;= this.size ? [set, this] : [this, set]; smallerSet.forEach((item) =&gt; { biggerSet.has(item) &amp;&amp; intersectionSet.add(item); }); return intersectionSet; }</pre><div class="contentsignin">Copy after login</div></div>

Symmetric difference set

intersectionDifference##intersectionDifference

The operation will return a set that contains all elements that have no intersection between the two sets. New collection.

intersectionDifference(set) {
    if (!this._isValid(set)) return new SetHelper();
    return new SetHelper([
        ...this.difference(set),
        ...set.difference(this),
    ]);
}
Copy after login
subset

subset

<p><code>isSubset 操作将判断两个集合是否为子集关系(当一个集合的所有项都包含在另一个集合中时)。实现上首先检查两个集合的大小,如果一个集合更大,则它不能是另一个集合的子集,然后对于每个项目,它检查它是否存在于另一个中。

isSubset(set) {
    if (!this._isValidSet(set)) return false;
    return (
        this.size <= set.size && [...this].every((item) => set.has(item))
    );
}
Copy after login

超集 superset

isSuperset 操作将判断两个集合是否为超集关系。超集是子集的反操作。当一个集合包含另一个较小或相等大小的集合的所有项目时,它就是一个超集。

isSuperset(set) {
    if (!this._isValidSet(set)) return false;
    return (
        this.size >= set.size && [...set].every((item) => this.has(item))
    );
}
Copy after login

静态 Set

静态Set 是一个始终包含它初始化元素的集合,不能添加、删除、清除元素。Javascript Set 不是静态的,它总能在创建后可以公开修改该集合的方法,如 adddelete ,为避免集合被修改,可以创建一个新的 Set ,将其修改方法重置 。

class StaticSet extends SetHelper {
    constructor(items) {
        super(items);

        this.add = undefined;
        this.delete = undefined;
        this.clear = undefined;
    }
}
Copy after login

使用

现在就可以使用上面定义的方法操作两个 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 ]
Copy after login

总结

Set 不限于上面这些操作,之前有介绍过可以用来合并数组去重,由于 SetArray 相互转换很简单,因此可以用到 Array 的场合可以优先考虑一下 Set ,因为在内存使用上, SetArray 占用更少。

更多编程相关知识,请访问:编程视频!!

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!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

See all articles