ES6 Set和Map数据结构
文章目录
Set是ES6的一种新的数据结构,特点是不存在值相同的成员
Set
Set本身是一个构造函数,用来生成Set数据结构
const set = new Set();[1,2,2,3,4,5,6,7,5,8,9].forEach((x)=>{
set.add(x);
})console.log(set); // [1,2,3,4,5,6,7,8,9]
Set构造方法接受一个数组或类数组作为参数完成初始化
const set = new Set([1,2,2,3,4,5,6,7,5,8,9])console.log(set); // [1,2,3,4,5,6,7,8,9]
Set实例对象存在size属性,等同于数组中的length
利用Set数据结构完成数组去重
const newArr = [...new Set([1,2,2,3,4,5,5])]console.log(newArr); // [1,2,3,4,5]
利用Set数据结构完成字符串去重
const newStr = [...new Set("ababcc")].join('');console.log(newStr); //"abc"
Set内部采用类似===方式检测每个成员是否相等,但不会发生类型转换,如5和"5",Set将他们判定为两个不同的值,如果是两个NaN,则为相等的值,那么Set只会保存其中一个,例外的是两个空对象{}被视为不同的值

Set结构的实例有以下属性
Set.prototype.constructor 构造方法,默认为Set函数Set.prototype.size 返回Set实例成员总数
Set的四个操作数据的方法
Set.prototype.add(value) //添加某个值,返回Set结构本身,可以链式操作Set.prototype.delete(value) //删除某个值,返回一个布尔值,表示删除是否成功
Set.prototype.has(value) //返回一个布尔值,表示该值是否为Set的成员
Set.prototype.clear() //清空Set实例的所有值,无返回值
Object和Set判断是否包含某个键的区别
//Objectconst properties = {
width:"1",
height:"1",
}
if(properties["width"]){
console.log("存在width");
}// Set
const properties = new Set();
properties.add("width").add("height");
if(properties.has("width")){
console.log("存在width");
}
使用Array.from()将Set数据结构转换成数组
const items = new Set([1,2,3,4,5]);const array = Array.from(items);
console.log(array); // [1,2,3,4,5]
使用Array.from()和Set完成数组去重
function dedupe(array){return Array.from(new Set(array));
}
const res = dedupe([1,2,2,3,4,5]);
console.log(res); //[1,2,3,4,5];
Set结构实例的四种遍历器
Set.prototype.key() //返回键名的遍历器Set.prototype.value() //返回键值的遍历器
Set.prototype.entries() //返回键值对的遍历器
Set.prototype.forEach() //使用回调函数遍历每个成员
Set的遍历顺序就是插入顺序
Set没有键名,只有键值(键名即键值)
可以省略keys()或values()方法直接使用for...of遍历Set
与数组的forEach一致,forEach接受两个参数,第一个是回调函数,参数分别为键值,键名,结构本身,第二个参数是回调函数绑定的this指向
拓展运算符(...)使用在Set结构上内部机制为for...of,因此可以使用拓展运算符实现数组去重操作,此外也可以间接实现Set结构的map和filter遍历
//数组去重[...new Set([1,2,2,3,4])] // [1,2,3,4]
const set = new Set([1,2,3,4]);
//Set的map遍历
const res = new Set([...set].map(v=>v*2));
console.log(res) //Set [2,4,6,8]
//Set的filter遍历
const res2 = new Set([...set].filter(v=>v>2));
console.log(res) //Set [3,4]
使用Set实现并集(Union)、交集(Intersect)和差集(Difference)
// Union并集let a = new Set([1,2,3,4]);
let b = new Set([3,4,5,6]);
const res = new Set([...a,...b]);
console.log(res) //Set [1,2,3,4,5,6]
//Intersect交集
const intersect = new Set([...a].filter(v=>b.has(v)));
console.log(intersect) //Set [3,4]
//Difference差集
const Difference = new Set([...a].filter(v=>!b.has(v)));
//a相对于b的差集
console.log(Difference); //Set [1,2]
改变Set结构内部成员
目前不能直接改变Set结构,但可以通过Set映射或Array.from()间接实现
const set = new Set([1,2,3,4]);
set = new Set([...set].map(v=>v*2));
console.log(set) // Set [2,4,6,8];
set = new Set(Array.from(set,val=>val*2))
console.log(set) //Set [4,8,12,16];
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论