ECMAScript6--11.Set-Map数据结构

2017-10-21  本文已影响21人  飞菲fly

1.数据结构

2.怎么用?什么场景用?

  {
    let list = new Set();
    list.add(1);
    list.add(2);
    //这个是没有成功添加进去的;添加重复的是不会报错的,只是不会生效而已;
    list.add(1); 
    
    console.log('list',list); //list  Set{1,2}

    //Set使用很重要的一个场景就是去重;
    //*它在转换元素的时候,不会做数据类型一个转换;
    let arr =[1,2,3,1,2];
    //let arr =[1,2,3,1,'2'];
    let list2 = new Set(arr);
    
    console.log('unique',list2); //unique Set{1,2,3}
    //console.log('unique',list2); //unique Set{1,2,3,'2'}
 
}
{
    let arr =['add','delete','clear','has'];
    let list = new Set(arr);
    
    
    for(let key of list.keys()){
    
        console.log('keys',key); 
        //keys add
        //keys delete
        //keys clear
        //keys has
    }
    
    for(let value of list.values()){
    
        console.log('value',value); 
        //value add
        //value delete
        //value clear
        //value has
    }
    
    for(let value of list){
    
        console.log('value',value); 
        //value add
        //value delete
        //value clear
        //value has
    }
    
    for(let [key,value] of list.entries()){
    
        console.log('entries',key,value); 
        //entries add  add
        //entries delete  delete
        //entries clear  clear
        //entries has   has
    }
    
    list.forEach(function(item){
        console.log(item);
    });
    //add
    //delete
    //clear
    //has
}
{ 
    let weakList = new WeakSet();
    let arg = {};
    
    weakList.add(arg);
    //weakList.add(2); //会报错,无效的值used in weak set;
    
    console.log('weakList',weakList); //weakList weakSet{Object{}}
}
{
    let map = new Map();
    let arr = ['123'];
    
    map.set(arr,456);
    console.log('map',map,map.get(arr)); 
    //map Map{["123"] =>456} 456
}
{
    let map = new Map([['a',123],['b',456]]);
    console.log('map args',map);
    //map args Map{"a" =>123,"b" =>456}

    //获取map对象有多少个元素;
    console.log('size',map.size); //size 2
    
    //获取某一个用get;
    
    //删除:delete
    console.log('delete',map.delete('a'),map);
    //delete  true  Map{"b" =>456}
    
    //清空clear
    console.log('clear',map.clear(),map);
    //clear undefined  Map{}
    
    //Map的遍历和Set用法是一样的,keys、values、entries、forEach
}
上一篇下一篇

猜你喜欢

热点阅读