Set是ES6提供的新对象类型。它不过是唯一的值观的集合。值可以是简单的原语,例如字符串,整数等,也可以是复杂的对象类型,例如对象文字或数组。
语法
new Set([iterable]);
这是一个可迭代的对象,其元素将添加到新集中。如果未提供iterable或传递了null值,则新集合将为空。
由于集合仅允许唯一值,因此在集合中添加一些现有元素之后对象的长度将不会更改。
<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
设置还显示布尔值。他们检查给定集中提供的元素是否可用,并执行布尔输出。
<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