本文共 2006 字,大约阅读时间需要 6 分钟。
1.无序
2.不重复
ES6的新的数据结构,类似于数组,但是元素是唯一的,而且没有顺序。
let s = new Set();
下面例子:10和10重复了,故只输出一个10;
两个对象看似重复了,其实没有,(这时两个内存地址不同的对象,只是值相同了,本质是不同的)let s = new Set([30,40]);s.add(10)s.add(20)s.add(10)s.add(true)s.add("10")s.add("10")s.add(new String("hello"));s.add(new String("hello"));console.log(s);//30,40,10,20,tue,"10",String,String
返回该set集合中的元素的个数。
set.size();
往set集合中添加一个元素,返回Set本身。
删除指定的值,返回一个布尔值,表示删除是否成功。
var arr = ["wo", "shi", "wo", 5]; let s = new Set(arr); console.log(delete(s.wo));//true console.log(s);
判断指定的值是否在set
中存在,返回一个布尔值。
let s = new Set([30, 40]); s.has(30);//判断有没有30 console.log( s.has(30));//true
清除所有的元素。没有返回值
let s = new Set([30, 40]); s.clear(); console.log(s);//{ }
Array.from方法可以将Set集合转为数组。
const arr = Array.from(s);
rest参数 三个点
const arr2 = [...s];
var arr = [10,20,20,30,50,30];//10,20,30,50var set = new Set(arr);arr = Array.from(set);console.log(arr);//封装成一个数组去重的方法 var arr = [2, 3, 45, 2]; function noDupli(array) { return Array.from(new Set(array)); } console.log(noDupli(arr));//[2, 3, 45]
返回键名遍历器
返回键的值的遍历器
返回键值对的遍历器
/这里是 for of 遍历的知识 var set = new Set([2, 3, 4, 5]); //下面是四种方法 for (const item of set.keys()) { console.log(item); } for (const item of set.values()) { console.log(item); } for (const item of set.entries()) { console.log(item); } for (const item of set) { console.log(item); }
是键值对的集合。与对象中的属性与属性值很类似,但是对象中的属性名只能是字符串。值–值的对应,字符串–值的对应。
let map = new Map();
键的唯一,而不是值的唯一。
返回map中有多少个键值对。
往map集合中添加一个key-value的键值对,返回map本身。如果key存在,原值会被覆盖。
通过键查找对应的键值对,将其删除,返回一个布尔值,表示删除是否成功。
判断指定的键是否在map
中存在,返回一个布尔值。
清除所有的元素。没有返回值
读取key对应的键值,如果找不到,返回undefined
返回键名遍历器
返回键的值的遍历器
返回键值对的遍历器
转载地址:http://oydyf.baihongyu.com/