前言
当我们需要存储一些数据的时候,首先想到的是定义一个变量用来存储,之后我们可能学了数组,发现数组比变量可以存储更多的数据,接着可能有其它的存储数据的方法等等,然而我今天需要介绍的是在es6中比较常见使用的数据类型结构,set和map。
set数据结构
一、set简介
set中成员的值都是唯一的,没有重复的值
向set中添加成员时,不会发生类型转换
向set中添加的对象总是不想等
二、常用的属性和方法
属性:
size:返回set实例的成员总数
方法:
add():添加某个值,返回set本身
delete():删除某个值,返回一个布尔值,判断删除是否成功
has():返回一个布尔值,表示该值是否为set成员
clear():清除所有成员,没有返回值
keys():返回键名的遍历器
values():返回键值的遍历器
entries():返回键值对的遍历器
foreach():使用回调函数遍历每个成员
三、实例剖析
为了方便大家更好的了解和学习set,我在这里会将这些方法和属性进行分类整理和讲解
1、set的基本用法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>数组去重</title> </head> <body> <script type="text/javascript"> const set=new set(); //创建set数据结构 [1,1,2,3,4,5].foreach(x=>{ set.add(x); }) console.log(set); //1,2,3,4,5 for(let i of set){ console.log(i); } </script> </body> </html>
可以看到向set添加成员时,不会添加重复的值
2、数组作为参数传入到set结构中
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <script type="text/javascript"> // const set=new set([1,2,3]); // console.log(...set);//1,2,3,使用扩展运算符 const set=new set(document.queryselectorall('div')); console.log(set.size);//5 size返回set实例的成员总数 //如上代码相当于 const item=new set(); document.queryselectorall('div').foreach(x=>{ item.add(x); }) console.log(item); console.log(item.size);//5 </script> </body> </html>
3、set中添加的值不会发生类型转换
<!doctype html> <html> <head> <meta charset="utf-8"> <title>向set中添加成员时,不会发生类型转换</title> </head> <body> <script type="text/javascript"> let myset=new set(); myset.add(5); myset.add('5'); console.log(myset);//5,'5' let set=new set(); let a=nan; let b=nan; set.add(a); set.add(b); console.log(set);//nan </script> </body> </html>
向 set 加入值的时候,不会发生类型转换,所以5
和"5"
是两个不同的值。set 内部判断两个值是否不同,使用的算法叫做“same-value-zero equality”,它类似于精确相等运算符(===)
,主要的区别是向 set 加入值时认为nan
等于自身,而精确相等运算符认为nan
不等于自身。
4、set中添加的对象总是不想等的
<!doctype html> <html> <head> <meta charset="utf-8"> <title>向set中添加的对象总是不想等</title> </head> <body> <script type="text/javascript"> let set=new set(); set.add({});//向set中添加一个空对象 console.log(set.size);//1 set.add({});//向set中添加另一个空对象 console.log(set.size);//2 </script> </body> </html>
由于两个空对象不相等,所以它们被视为两个值
5、array.from()方法
array.from()可以将set结构转为数组,这就提供了去除数组重复成员的另一种方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>array.from()方法</title> </head> <body> <script type="text/javascript"> const items=new set([1,2,3,4,5]); console.log(items);//1,2,3,4,5 const array=array.from(items); console.log(array);//1.2.3,4,5 //array.from()方法实现数组去重 function dedupe(arr){ return array.from(new set(arr)) } console.log(dedupe([1,1,2,3]));//1,2,3 </script> </body> </html>
四.遍历的应用
1、数组去重
<!doctype html> <html> <head> <meta charset="utf-8"> <title>数组去重</title> </head> <body> <script type="text/javascript"> let set=new set(['red','blue','green']); let arr=[...set]; console.log(arr);//red,blue,green //数组去重 let arrs=[1,1,3,3,4,5,6]; let unique=[...new set(arrs)]; console.log(unique);//1,3,4,5,6 </script> </body> </html>
2、间接使用数组的方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>间接使用数组的方法</title> </head> <body> <script type="text/javascript"> let set=new set([1,2,3,4,5]); set=new set([...set].map(x=>x*2));//使用数组的map方法 console.log(set);//2,4,6,8,10 let myset=new set([1,2,3,4,5]); myset=new set([...myset].filter(x=>x%2==0));//使用数组的filter方法 console.log(myset);//2,4 </script> </body> </html>
3、实现并集,交集,差集
<!doctype html> <html> <head> <meta charset="utf-8"> <title>实现并集,交集,差集</title> </head> <body> <script type="text/javascript"> let a=new set([1,2,3]); let b=new set([4,3,2]); //并集 let union=new set([...a, ...b]); console.log(union);//1,2,3,4 //交集 let intersect=new set([...a].filter(x=>b.has(x))); console.log(intersect);//2,3 //差集 let difference=new set([...a].filter(x=>!b.has(x))); console.log(difference);//1 </script> </body> </html>
4、同步改变原来的 set 结构
如果想在遍历操作中,同步改变原来的 set 结构,目前没有直接的方法,但有两种变通方法。一种是利用原 set 结构映射出一个新的结构,然后赋值给原来的 set 结构;另一种是利用array.from
方法。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>同步改变原来的 set 结构</title> </head> <body> <script type="text/javascript"> //方法一 let set=new set([1,2,3]); set=new set([...set].map(val=>val*2)); console.log(set);//2,4,6 //方法二 let myset=new set([1,2,3]); myset=new set(array.from(myset,val=>val*2)); console.log(myset);//2,4,6 </script> </body> </html>
五、set实例属性和方法
1、size属性
<!doctype html> <html> <head> <meta charset="utf-8"> <title>set中的size属性</title> </head> <body> <script type="text/javascript"> const set=new set(); //向set中添加成员 set.add(1); set.add(2); set.add(3); //链式方法 set.add(4).add(5).add(6); console.log(set.size);//6 </script> </body> </html>
2、操作方法add()、delete()、has()、clear()
<!doctype html> <html> <head> <meta charset="utf-8"> <title>set中的操作方法add()、delete()、has()、clear()</title> </head> <body> <script type="text/javascript"> const set=new set(); //向set中添加成员 set.add(1); set.add(2); set.add(3); //链式方法 set.add(4).add(5).add(6); console.log(set.size);//6 console.log(set.has(1));//true set.delete(1); console.log(set.has(1));//false set.clear();//清空全部set成员 console.log(set.size);//0 </script> </body> </html>
3、遍历方法keys()、values()、entries()、foreach()
注意:set的遍历顺序就是插入顺序,由于set没有键名,只有键值(或者说键名和键值是同一个值),所以keys()和values()方法的行为完全一致
<!doctype html> <html> <head> <meta charset="utf-8"> <title>set中的遍历方法keys(),values(),entries(),foreach()</title> </head> <body> <script type="text/javascript"> let set=new set(['red','blue','green']); //遍历全部的key for(let key of set.keys()){ console.log(key);//red,blue,green } //遍历全部的value for(let value of set.values()){ console.log(value);//red,blue,green } //遍历全部的key和value for(let item of set.entries()){ console.log(item);//['red','red'],['blue','blue'],['green','green'] } set.foreach((key,value)=>{ console.log(key+':'+value); }) </script> </body> </html>
map数据结构
一、map简介
es6中的map很大程度上和set相似,但是map是以键值对的形式存储数据的
二、常用的属性和方法
属性:
size:返回map结构的成员总数
方法:
set(key,value):设置键名key对应的键值value,然后返回整个map结构,如果key已经有值,则键值会被更新,否则就新生成该键
get(key):读取key对应的键值,如果找不到key,则返回undefined
has(key):返回一个布尔值,表示某个键是否在当前map对象中
delete(key):删除某个key,返回true,如果删除失败,返回false
clear():清除所有成员,没有返回值
keys():返回键名的遍历器
values():返回键值的遍历器
entries():返回键值对的遍历器
foreach():遍历map的所有成员
三、实例剖析
1、size属性
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的size属性</title> </head> <body> <script type="text/javascript"> const map=new map(); map.set('foo',true); map.set('bar',false); console.log(map.size);//2 </script> </body> </html>
2、set(key,value)方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的set()方法</title> </head> <body> <script type="text/javascript"> const map=new map(); map.set('1','a');//键是字符串 map.set(2,'b');//键是数值 map.set(undefined,'3');//键是undefined console.log(map);//'1'=>a,2=>b,undefinde=3 const mymap=new map(); //链式写法 mymap.set(1,'a').set(2,'b').set(3,'c'); console.log(mymap);//1=>a,2=>b,3=>c </script> </body> </html>
3、get(key)方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的get()方法</title> </head> <body> <script type="text/javascript"> const map=new map(); const hello=function(){ console.log('你好'); } map.set(hello,'es6');//键是函数 console.log(map.get(hello));//es6 </script> </body> </html>
4、has(key)方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的has()方法</title> </head> <body> <script type="text/javascript"> const map=new map(); //链式写法 map.set('a',1).set('b',2).set('c',3);//向map中添加成员 console.log(map.has('a'));//true console.log(map.has('b'));//true console.log(map.has('c'));//true console.log(map.has('d'));//false </script> </body> </html>
5、delete(key)方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的delete方法</title> </head> <body> <script type="text/javascript"> const map=new map(); map.set('a',1); console.log(map.has('a'));//true map.delete('a');//删除键a console.log(map.has('a'));//false </script> </body> </html>
6、clear()方法
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map中的clear()方法</title> </head> <body> <script type="text/javascript"> const map=new map(); map.set('foo',true);//向map中添加成员 map.set('bar',false); console.log(map.size);//2 map.clear();//清除map中的全部成员 console.log(map.size);//0 </script> </body> </html>
7、遍历方法keys()、values()、entries()、foreach()
<!doctype html> <html> <head> <meta charset="utf-8"> <title>遍历方法keys(),values(),entries(),foreach()</title> </head> <body> <script type="text/javascript"> const map=new map(); //向map中添加成员 map.set(1,'a'); map.set(2,'b'); map.set(3,'c'); //遍历全部的键 for(let key of map.keys()){ console.log(key);//1,2,3 } //遍历全部的值 for(let values of map.values()){ console.log(values);//a,b,c } //遍历全部的键和值 for(let [key,value] of map.entries()){ console.log(key,value);//1=>a,2=>b,3=>c } for(let item of map.entries()){ console.log(item[0],item[1]);//1=>a,2=>b,3=>c } for(let [key,value] of map){ console.log(key,value);//1=>a,2=>b,3=>c } map.foreach(function(value,key){ console.log(key,value); }) </script> </body> </html>
注意:
这里的foreach()是值在前,键在后
8、map结构转为数组
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map结构转为数组</title> </head> <body> <script type="text/javascript"> const map=new map([ [1,'one'], [2,'two'], [3,'three'] ]); console.log([...map.keys()]);//[1,2,3] console.log([...map.values()]);//one,two,three console.log([...map]);//[1,one],[2,two],[3,three] console.log([...map.entries()]);//[1,one],[2,two],[3,three] const map1=new map( [...map].filter(([key,value])=>key<3)//使用数组的filter方法 ); console.log(map1);//1=>one,2=>two </script> </body> </html>
三、map与其它数据结构的转换
作为键值对存储数据的map与其它数据也可以进行转换,我们看下下面的案例
1、map转为数组
map转为数组最方便的方法,就是使用扩展运算符...
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map转为数组</title> </head> <body> <script type="text/javascript"> const map=new map();//创建map数据结构 map.set(true,7);//向map中添加成员 map.set({foo:3},['abc']); console.log([...map]);//[[true,7],[{foo:3},['abc']]]; </script> </body> </html>
2、数组转为map
将数组传入map构造函数,就可以转为map
<!doctype html> <html> <head> <meta charset="utf-8"> <title>数组转为map</title> </head> <body> <script type="text/javascript"> const map=new map([ [true,7], [{foo:3},['abc']] ]); console.log(map); //map{ //true=>7, //object:{foo:3}=>['abc']; //} </script> </body> </html>
3、map转为对象
如果所有map的键都是字符串,它可以无损的转为对象,如果有非字符串的键名,那么这个键名会被转为字符串,再作为对象的键名
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map转为对象</title> </head> <body> <script type="text/javascript"> function strmapobj(strmap){ let obj=object.create(null);//创建一个新对象 for(let [key,value] of strmap){//遍历循环strmap obj[key]=value; } return obj; } const map=new map().set('yes',true).set('no',false); console.log(strmapobj(map));//{yes:true,no:false} </script> </body> </html>
在这里了我需要讲解一下object.create()这个方法,官方的意思是:object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
<!doctype html> <html> <head> <meta charset="utf-8"> <title>测试object.create()方法</title> </head> <body> <script type="text/javascript"> const person={ ishuman: false, printintroduction: function () { console.log(this.name,this.ishuman); } } const me = object.create(person); me.name = "matthew"; me.ishuman = true; me.printintroduction();//mattew,true </script> </body> </html>
4、对象转为map
<!doctype html> <html> <head> <meta charset="utf-8"> <title>对象转为map</title> </head> <body> <script type="text/javascript"> function objtomap(obj){ let map=new map(); for(let key of object.keys(obj)){ map.set(key,obj[key]); } return map; } console.log(objtomap({yes:true,no:false}));//yes=>true,no=>false </script> </body> </html>
在这里讲解object.keys()方法,官方解释:object.keys()
方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用,for..in循环遍历该对象时返回的顺序一致 。如果对象的键-值都不可枚举,那么将返回由键组成的数组。
参数:
要返回其枚举自身属性的对象
返回值:
一个表示给定对象的所有可枚举属性的字符串数组
// simple array var arr = ['a', 'b', 'c']; console.log(object.keys(arr)); // console: ['0', '1', '2'] // array like object var obj = { 0: 'a', 1: 'b', 2: 'c' }; console.log(object.keys(obj)); // console: ['0', '1', '2'] // array like object with random key ordering var anobj = { 100: 'a', 2: 'b', 7: 'c' }; console.log(object.keys(anobj)); // console: ['2', '7', '100'] // getfoo is a property which isn't enumerable var myobj = object.create({}, { getfoo: { value: function () { return this.foo; } } }); myobj.foo = 1; console.log(object.keys(myobj)); // console: ['foo']
5、map转为json字符串
map转为json要区分两种情况,一种情况时map的键名都是字符串,这时可以选择转为对象json,另一种情况是map的键名有非字符串,这时可以选择转为数组json。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>map转为json</title> </head> <body> <script type="text/javascript"> function strmaptoobj(strmap){ let obj=object.create(null);//创建一个新对象 for(let [key,value] of strmap){ obj[key]=value; } return obj; } function strmaptojson(strmap){ return json.stringify(strmaptoobj(strmap)); } let map=new map().set('yes',true).set('no',false); let obj=strmaptojson(map); console.log(obj);//{'yes':true,'no':false} function maptoarrayjson(map){ return json.stringify([...map]); } let foomap=new map().set(true,7).set({foo:3},['abc']); let foo=maptoarrayjson(foomap); console.log(foo);//[[true:7],[{foo:3},['abc']]] </script> </body> </html>
6、json字符串转为map
json转为map,正常情况下所有键名都是字符串,但是有一种特殊情况,整个json就是一个数组,且每个数组成员本身,又是一个有两个成员的数组,这时它可以一一对应的转为map,这往往是map转为数组json的逆操作。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>json转为map</title> </head> <body> <script type="text/javascript"> function objtostrmap(obj){ let map=new map(); for(let key of object.keys(obj)){ map.set(key,obj[key]); } return map; } function jsontostrmap(jsonstr){ return objtostrmap(json.parse(jsonstr)); } let obj1=jsontostrmap('{"yes": true, "no": false}') console.log(obj1);//yes=>true,no=>false function jsontomap(jsonstr){ return new map(json.parse(jsonstr)); } let obj2=jsontomap('[[true,7],[{"foo":3},["abc"]]]')//true=>7,{foo:3}=>['abc'] console.log(obj2); </script> </body> </html>
总结
本章我们主要学习了es6中set和map相关的属性和方法,set和map的方法中有很多都是相同的方法,has()、delete()、clear()、keys()、values()、entries、foreach()等等。
到此这篇关于es6学习总结之set和map的使用的文章就介绍到这了,更多相关es6学习总结之set和map的使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论