解释 JavaScript 中的集合?
javascriptobject oriented programmingprogramming更新于 2025/7/18 1:16:17
集合
集合是 ES6 提供的一种新对象类型。它只不过是一个值的集合,这些值都是唯一的。这些值可以是简单的原语,例如字符串、整数等,也可以是复杂的对象类型,例如对象文字或数组。
语法
new Set([iterable]);
参数
iterable
它是一个可迭代对象,其元素将添加到新集合中。如果没有提供可迭代对象或者传递了空值,那么新集合将为空。
示例
由于集合只允许唯一值,因此在集合中添加一些现有元素后对象的长度不会改变。
<html>
<body>
<script>
var set1 = new Set(["a","a","b","b","c"]);// no of unique elements - 3(a, b and c)
set1.add('c').add('d') // Two elements were added (c,d)
set1.forEach(alphabet => { // In total 7 elements but only 4 unique values
document.write(`alphabet ${alphabet}!`);
document.write("</br>");
});
document.write(set1.size); // it displays 4 since sets accept only unique values.
</script>
</body>
</html>
输出
alphabet a! alphabet b! alphabet c! alphabet d! 4
示例 2
集合也显示布尔值。它们检查给定集合中提供的元素是否可用,并执行布尔输出。
<html>
<body>
<script>
var set1 = new Set(["a","a","b","b","c"]);
set1.add('c').add('d')
set1.forEach(alphabet => {
document.write(`alphabet ${alphabet}!`);
document.write("</br>");
});
document.write(set1.has('a')); // it display true because a is there in set1
document.write("</br>");
document.write(set1.has('8')); // it display false because there is no 8 in the set1.
document.write("</br>");
document.write(set1.size); // displays only unique values because only unique values are accepted
</script>
</body>
</html>
输出
alphabet a! alphabet b! alphabet c! alphabet d! true false 4
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

