1、Set定义
Set数据结构类似于数组,但它成员是唯一不重复的,常用Set定义:
<script>
const arrays = [1,2,3,4,5,6,7];
arrays.push(8);
arrays.push(1);
const set = new Set();
arrays.forEach(item=>{
set.add(item);
});
const set2 = new Set(arrays);
console.log(set2);
const set3 = new Set([1,2,3,4,5,6,7,8]);
console.log(set3);
const setStr = new Set("abcdefg");
console.log(setStr);
</script>
2、Set属性
<script>
const setStr = new Set("aabbccddeeffgg");
console.log(setStr.size); //size返回成员总数
</script>
3、Set方法
<script>
const setStr = new Set("aabbccddeeffgg");
setStr.add("aaa"); //添加元素
setStr.delete("a"); //删除元素
console.log(setStr.has("b")); //是否包含某个元素
setStr.clear(); //清除元素
console.log(setStr);
</script>
4、Set扩展
<script>
const set3 = new Set([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(set3);
console.log(...set3);
console.log([...set3]);
</script>
5、set对字符串去重
<script>
const setStr = new Set("aabbccddeeffgg");
var str = [...setStr].join("");
console.log(str);
</script>