JavaScript 中的 Set.add() 方法用于向 Set 对象添加新元素。集合是唯一值的集合,即每个元素都必须是唯一的。如果我们尝试添加此集合中已有具有相同值的元素,它将忽略重复的值并保持唯一性。
语法
以下是 JavaScript Set.add() 方法的语法 -
add(value)
参数
此方法接受以下参数 -
- value - 要添加到 Set 的值。
返回值
此方法返回 Set 对象本身以及添加的值。
示例 1
在下面的示例中,我们使用 JavaScript Set.add() 方法将数字 5 和 10 插入到“数字集”集中 -
<html>
<body>
<script>
const numberSet = new Set();
numberSet.add(5);
numberSet.add(10);
document.write(`Result: ${[...numberSet]}`);
</script>
</body>
</html>
如果我们执行上述程序,提供的 integer 元素将被添加到集合中。
示例 2
如果我们传递一个在这个集合中已经具有相同值的新元素,它会忽略重复的值 -
<html>
<body>
<script>
const numberSet = new Set();
numberSet.add(5);
numberSet.add(5);
numberSet.add(5);
numberSet.add(10);
document.write(`Result: ${[...numberSet]}`);
</script>
</body>
</html>
正如我们在输出中看到的那样,重复的值被忽略,并且集保持唯一性。
示例 3
在此示例中,我们将字符串元素插入到 “stringSet” 集合中 -
<html>
<body>
<script>
const stringSet = new Set();
stringSet.add("QikepuCom");
stringSet.add("Qikepu");
document.write(`Result: ${[...stringSet]}`);
</script>
</body>
</html>
执行上述程序后,提供的 string 元素将被添加到 set 中。
示例 4
在此示例中,我们使用 add() 方法将两个对象添加到 “objectSet” 集中 -
<html>
<body>
<script>
const objectSet = new Set();
const obj1 = { Firstname: "Joe" };
const obj2 = { Lastname: "Goldberg" };
objectSet.add(obj1).add(obj2);
document.write(`Result: ${JSON.stringify([...objectSet])}`);
</script>
</body>
</html>
正如我们在输出中看到的那样,对象值已添加到集合中。
示例 5
以下示例将布尔值 true 和 false 插入到 “booleanSet” 集合中 -
<html>
<body>
<script>
const booleanSet = new Set();
booleanSet.add(true);
booleanSet.add(false);
document.write(`Result: ${[...booleanSet]}`);
</script>
</body>
</html>
执行程序后,该集合包含 “true” 和 “false” 作为元素。