Home > Article > Web Front-end > 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
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
.
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:
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
Setmozilla website.
Set , let’s describe the applicable occasions, mainly the set operations in the data:
Set based on these three occasions.
Operations
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:js;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!