Javascript 简明教程
JavaScript - Sets
JavaScript Set 对象是唯一值的集合。每个值只能在 Set 中出现一次。 Set 可以包含任何数据类型的任何值。在 ECMAScript 6 (ES6) 中向 JavaScript 中引入了集合。
A JavaScript Set object is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type. The sets are introduced to JavaScript in ECMAScript 6 (ES6).
JavaScript 集合与数组相差不大,但有一些关键差异:
JavaScript Sets are similar to Arrays, but there are some key differences:
-
Sets can only hold unique values, while Arrays can hold duplicate values.
-
Sets are not ordered, while Arrays are ordered.
-
Sets are faster to add and remove items from than Arrays.
JavaScript 集合经常用来存储唯一值,如访问过网站的唯一用户。它还可以用来从数组中删除重复值。
JavaScript Sets are often used to store unique values, such as the unique users who have visited a website. They can also be used to remove duplicate values from an Array.
Syntax
用户可以遵循下面的语法在 JavaScript 中定义一个集合 −
Users can follow the syntax below to define a set in JavaScript −
let set1 = new Set([iterable]);
在上面的语法中,我们使用了 Set() 构造函数和 'new' 关键字来定义一个集合。
In the above syntax, we used the Set() constructor function with a ‘new’ keyword to define a set.
Parameters
-
*Iterable− * It is an optional parameter. The Set() constructor function traverses through the elements of the iterable and creates a new set using those elements.
Examples
Example (Access set elements)
在下面的示例中,我们传递了包含重复元素的数组作为 Set() 构造函数的参数。num_set 仅包含唯一值。
In the example below, we have passed the array containing the duplicate elements as an argument of the Set() constructor function. The num_set contains only unique values.
我们使用 values() 方法来获取值集合的迭代器。要遍历迭代器,我们使用 for…of 循环。在循环中,我们访问元素并打印它。您可以观察到,即使输入数组包含重复的元素,集合也会包含唯一的值。
We used the values() method to get the iterator of the set values. To traverse the iterator, we use the for…of loop. In the loop, we access the element and print it. You can observe that set contains unique values even if the input array contains duplicate elements.
<html>
<body>
<p>The set elements are: </p>
<p id = "output"></p>
<script>
const num_set = new Set([10, 20, 20, 20]);
for (let value of num_set.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
The set elements are:
10
20
Example (Insert elements into the sets)
用户可以使用 add() 方法将元素插入集合。在此处,我们创建了空集合。之后,我们使用了 add() 方法 3 次,将 60、50、50 元素添加到集合中。
Users can use the add() method to insert the element into the set. Here, we have created the empty set. After that, we used the add() method 3 times to add the 60, 50, 50 elements into the set.
我们插入 50 两次,但集合只包含一次,因为它只包含唯一的值。
We inserted the 50 for 2 times, but the set contains only once as it contains unique values.
<html>
<body>
<p>Set elements after adding element/s to it: </p>
<div id = "output"> </div>
<script>
const num_set = new Set();
num_set.add(60);
num_set.add(50);
num_set.add(50);
for (let value of num_set.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
Set elements after adding element/s to it:
60
50
Example (Remove set elements)
集合的 delete() 方法允许您从集合中删除元素。在此处,我们创建了包含各种数字的集合,并使用了 delete() 方法从集合中删除 200 和 400。
The delete() method of the set allows you to delete the element from the set. Here, we created the set containing the various numbers and used the delete() method to delete the 200 and 400 from the set.
<html>
<body>
<p> After deleting elements from the set: </p>
<div id = "output"> </div>
<script>
let num_set = new Set([100, 200, 300, 400, 500]);
num_set.delete(200);
num_set.delete(400);
for (let value of num_set.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
The set contains 100?: true
Example (Check if the set contains a specific value)
下面的示例演示了如何使用 has() 方法检查集合是否包含特定的值。
The example below demonstrates of using the has() method to check whether the set contains the specific value.
在此处,我们检查集合是否包含 100,并在输出中相应地打印消息。
Here, we check whether the set contains 100 and print the message in the output accordingly.
<html>
<body>
<p id = "output">The set contains 100?: </p>
<script>
const num_set = new Set([100, 200, 300, 400, 500]);
document.getElementById("output").innerHTML += num_set.has(100);
</script>
</body>
</html>
它返回“true”,因为元素 100 存在于集合中。
It returns "true" because the element 100 is present in the set.
The set contains 100?: true
Mathematical set operations
Set 类不包含内置的方法来执行数学集合运算,如并集、交集或集合差集。因此,您需要编写自定义的 JavaScript 代码来执行数学运算,如下所示。
The Set class doesn’t contain the built-in methods to perform the mathematical set operations like union, intersection, or set difference. So, you need to write the custom JavaScript code to perform the mathematical operations as shown below.
Example (Union of two sets)
两个集合的并集包含 set1 和 set2 中所有唯一元素。
The union of two sets contains all unique elements of set1 and set2.
在下面的示例中,set1 和 set2 包含汽车名称。我们定义了“union”集合并将数组作为参数传递。我们使用了展开运算符来创建包含 set1 和 set2 的元素的数组。
In the example below, set1 and set2 contain the car names. We have defined the ‘union’ set and passed the array as an argument. We used the spread operator to create an array containing the elements of set1 and set2.
<html>
<body>
<p>The Union of set1 and set2 is: </p>
<div id = "output"> </div>
<script>
const set1 = new Set(["BMW", "Audi", "TATA"]);
const set2 = new Set(["BMW", "TaTa", "Honda", "Suzuki"]);
const union = new Set([...set1, ...set2]); // Taking union
for (let value of union.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
如果我们执行程序,它将返回 set1 和 set2 中的所有唯一元素。
If we execute the program, it returns all unique elements of set1 and set2.
The Union of set1 and set2 is:
BMW
Audi
TATA
TaTa
Honda
Suzuki
Example (Intersection of two sets)
两个集合的交集包含同时存在于 set1 和 set2 中的唯一元素。
The intersection of two sets contains the unique elements which exist in set1 and set2 both.
此处,我们有两个包含汽车名称的集合,并定义了“inter”集合来存储存在于两个集合中的集合元素。
Here, we have two sets containing the car names and defined the ‘inter’ set to store the set elements which exist in both sets.
我们遍历 set1 的元素,并在循环内部使用 has() 方法来检查 set1 的元素是否存在于 set2 中。如果是,我们向“inter”集合添加一个元素。
We traverse through the elements of set1, and inside the loop we use the has() method to check whether the element of the set1 exists in the set2. If yes, we add an element into the ‘inter’ set.
<html>
<body>
<p> The intersection of set1 and set2 is: </p>
<p id = "output"> </p>
<script>
const set1 = new Set(["BMW", "Audi", "TATA"]);
const set2 = new Set(["BMW", "TATA", "Honda", "Suzuki"]);
const inter = new Set();
for (let car of set1) {
if (set2.has(car)) {
inter.add(car);
}
}
for (let value of inter.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
The intersection of set1 and set2 is:
BMW
TATA
Example (Difference of two sets)
set1 和 set2 之间的差集包含 set1 中但不在 set2 中的所有元素。
The difference between set1 and set2 contains all elements in the set1 but not in the set2.
我们创建了一个名为“diff”的新集合,并用“set1”元素对其进行初始化。之后,我们遍历 set2 元素。如果 set2 的任何元素存在于“diff”集合中,我们将删除它。
We have created the new set named ‘diff’ and initialized it with the ‘set1’ elements. After that, we traverse the set2 elements. If any element of the set2 exists in the ‘diff’ set, we delete it.
<html>
<body>
<p>The difference of set1 and set2 is: </p>
<div id = "output"> </div>
<script>
const set1 = new Set(["BMW", "Audi", "TATA"]);
const set2 = new Set(["BMW", "TATA", "Honda", "Suzuki"]);
const diff = new Set(set1);
for (let car of set2) {
diff.delete(car);
}
for (let value of diff.values()) {
document.getElementById("output").innerHTML += value + "<br> ";
}
</script>
</body>
</html>
The difference of set1 and set2 is:
Audi
JavaScript Set Reference
在 JavaScript 中,Set 是唯一值的集合。换句话说,每个值只能在集合中出现一次。它提供用于在集合中添加、删除和检查元素是否存在的方法。此处,我们列出了 Set 类的属性和方法。
In JavaScript, a Set is a collection of unique values. In other words, each value can occur only once within a set. It provides methods to add, remove, and check for the presence of elements in the set. Here, we have listed the properties and methods of the Set class.
JavaScript Set Constructor()
以下是 JavaScript 中 Set 的构造函数 −
Following is the constructor of Set in JavaScript −
Sr.No. |
Name & Description |
1 |
Set() Creates and returns the set of unique values from values passed as an argument. |
JavaScript Set Properties
以下是 Set 类属性——
Following are the properties of Set class −
Sr.No. |
Name & Description |
1 |
size This property returns the size of the set. |
JavaScript Set Methods
在下表中,我们列出了 Set 类的所有属性——
In the following table, we have listed all the properties of Set class −
Sr.No. |
Name & Description |
1 |
add() This method insert elements into the set. |
2 |
clear() This method removes removes all elements of the set. |
3 |
delete() This method deletes a single element of the set. |
4 |
difference() This method returns elements in first set but not in the second set. |
5 |
entries() To get an iterator containing all set entries. |
6 |
forEach() This method executes a provided function once for each value in this set. |
7 |
has() This method indicates whether an element with the specified value exists or not. |
8 |
intersection() This method returns the common elements in both sets. |
9 |
keys() This method is an alias for values() method. |
10 |
values() This method returns a new Set iterator object that containing values for each element in a Set object. |