Set数据结构
程序员文章站
2024-02-20 19:10:10
...
1.Set(集合):类似与数组,但成员的值是唯一的,不重复的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
let s = new Set();
s.add(10);
s.add("hello");
s.add(10);
console.log(s,s.size);
//判断它的长度使用size属性
</script>
</body>
</html>
2.数组转化为集合
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
let arr = [10,20,10,20,30,40];
// let s = new Set();
/* for (let i in arr){
s.add(arr[i]);
}
console.log(s);*/
/* arr.forEach(x => {
s.add(x);
})
console.log(s);*/
let s = new Set(arr);
let arr1 = Array.from(s);//集合转化为数组
</script>
</body>
</html>
3.set常用操作
3-1.add:添加成员
3-2:delete:删除成员
3-3:clear:清空
遍历set: forEach();
转载于:https://www.jianshu.com/p/58bd0db833d3