The "Set Methods" proposal introduces 7 new methods to JavaScript/ECMAScript:
-
union(setB): Returns a new
Set
containing all elements from the original set and another setsetB
. This method effectively combines the members of two sets without duplication. -
intersection(setB): Returns a new
Set
containing all elements that are present in both the original set and setsetB
. This method identifies common elements between two sets. -
difference(setB): Returns a new
Set
containing all elements that are in the original set but not in setsetB
. It helps in identifying elements that are unique to the first set when compared to another set. -
symmetricDifference(setB): Returns a new
Set
containing all elements that are in either of the sets but not in their intersection. This method is useful for finding elements that are in either one set or the other, but not in both. -
isSubsetOf(setB): Returns a boolean indicating whether the original set is a subset of set
setB
. A set is a subset of another set if all elements of the former are contained in the latter. -
isSupersetOf(setB): Returns a boolean indicating whether the original set is a superset of set
setB
. A set is a superset of another set if it contains all elements of the latter set. -
isDisjointFrom(setB): Returns a boolean indicating whether the original set and set
setB
have no elements in common. If they have no common elements, the sets are considered disjoint.
const setA = new Set([1, 2, 3, 4]);
const setB = new Set([3, 4, 5, 6]);
// Using union to combine two sets
const unionSet = setA.union(setB);
console.log('Union of setA and setB:', [...unionSet]);
// Using intersection to find common elements
const intersectionSet = setA.intersection(setB);
console.log('Intersection of setA and setB:', [...intersectionSet]);
// Using difference to find elements in setA not in setB
const differenceSet = setA.difference(setB);
console.log('Difference of setA from setB:', [...differenceSet]);
// Using symmetricDifference to find elements in either set but not in both
const symmetricDifferenceSet = setA.symmetricDifference(setB);
console.log('Symmetric Difference between setA and setB:', [...symmetricDifferenceSet]);
// Checking if setA is a subset of setB
const isSubset = setA.isSubsetOf(setB);
console.log('Is setA a subset of setB?', isSubset);
// Checking if setA is a superset of setB
const isSuperset = setA.isSupersetOf(setB);
console.log('Is setA a superset of setB?', isSuperset);
// Checking if setA is disjoint from setB
const isDisjoint = setA.isDisjointFrom(setB);
console.log('Are setA and setB disjoint?', isDisjoint);
标签:Operations,set,const,setA,setB,JavaScript,Set,elements From: https://www.cnblogs.com/Answer1215/p/18202898