一、基本用法
- Set 是一种新集合类型,为 JavaScript 这门语言带来了集合数据结构
- Set在很多方面都像是加强的 Map ,这是因为他们的大多数API 和行为都是共有的
- 它类似于数组,但是成员的值都是唯一的,没有重复的值。
- 被称之为:字典数组
- 语法:
const s = new Set()
const s = new Set(['hello','world','你好','世界']);
console.log(s[1]);
const s = new Set(['hello','world','你好','世界','hello','world']);
console.log(s);
const arr = [1,2,3,2,1];
const res = new Set(arr);
console.log(res);
console.log([...res]);
二、常用方法
1. 添加:add()
const s = new Set(['hello','world','你好','世界']);
s.add(true);
console.log(s);
add()
返回集合的实例,所以可以将多个添加操作连缀起来,包括初始化
const s = new Set().add("val1");
s.add("val2").add("val3")
console.log(s.size);
2. 删除:delete()
- 语法:
Set数据类型.delete(要删除的数据);
const s = new Set(['hello','world','你好','世界']);
s.delete('世界');
console.log(s);
delete()
返回一个布尔值,表示集合中是否存在要删除的值
const s = new Set().add("val1");
console.log(s.size);
console.log(s.delete("val1"));
console.log(s.delete("val1"));
3. 清除:clear()
- 语法:
Set数据类型.clear();
- 作用:清除所有数据
const s = new Set(['hello','world','你好','世界']);
s.clear();
console.log(s);
4. 遍历:forEach()
- 语法:
Set数据类型.forEach(function(item,item,set){});
const s = new Set(['hello','world','你好','世界']);
s.forEach(function(item,it,set){
console.log(item,'=>',it,'=>',set);
})
5. 遍历:for...of
- 语法:
for(let value of Set数据类型){};
- set数据结构使用不了for或for…in遍历
const s = new Set(['hello','world','你好','世界']);
for(let value of s){
console.log(value);
}
6. 判断:has()
- 语法:
Set数据类型.has(要判断的数据);
- 返回值:你要判断的数据是不是存在
true/false
const s = new Set(['hello','world','你好','世界']);
console.log(s.has('你好'));
7. 长度:size
- 语法:
Set数据类型.size;
- 作用:获取 set 数据结构里面有多少条数据
- set数据结构是没有
length
属性的
const s = new Set(['hello','world','你好','世界']);
console.log(s.size);
console.log(s.length);