Set,Map与Array,Object对比

Map与Array

数据结构横向对比,用Map和Array分别实现最基本的增删改查;

//增

{
let theMap=new Map();
let theArray=[];
theMap.set('t',1);
theArray.push({t:1});
console.log(theMap);     //Map(1) {"t" => 1}
console.log(theArray);   //[{t:1}]
} 

//删

theMap.delete('t');
let index=theArray.findIndex(item=>item.t);
theArray.splice(index,1);

//改

theMap.set('t',2);
let index=theArray.findIndex(item=>item.t);
theArray[index]={t:2};
//或者
theArray.foreach(item=>item.t?item.t=2:'');

//查

theMap.has('t');
theArray.find(item=>item.t);

总体来说,Map的操作更方便简洁一些。

Set与Array

数据结构横向对比,用Map和Array分别实现最基本的增删改查;

//增

{
let theSet=new Set();
let theArray=[];
theSet.add({t:1});
theArray.push({t:1});
console.log(theSet);     //{{t:1}}
console.log(theArray);   //[{t:1}]
} 

//删

theSet.forEach(item=>item.t?theSet.delete(item):'');
//因为保存的是对象,是引用类型,不能直接通过delete删除,需要用这种方法 
let index=theArray.findIndex(item=>item.t);
theArray.splice(index,1);

//改

theSet.forEach(item=>item.t?item.t=2:'');
//因为保存的是对象,是引用类型,不能通过add改,需要用这种方法    
theAarray.forEach(item=>item.t?item.t=2:'');

//查

  let set_exist=theSet.forEach(item=>item.t);  
//因为保存的是对象,是引用类型,通过has查不到,需要用这种方法      
  let array_exist=theArray.find(item=>item.t);

总体来说,Set储存对象,相对于数组没有明显优势。

Map,Set与Array

{
//因为Set遍历不到对象,所以把对象赋值
  let item={t:1};
  let map=new Map();
  let set=new Set();
  let obj={};

  //
  map.set('t',1);
  set.add(item);
  obj['t']=1;
  console.info(obj,map,set);

  // 删除
  map.delete('t');
  set.delete(item);
  delete obj['t'];
  console.info(obj,map,set);

  //
  map.set('t',2);
  item.t=2;
  obj['t']=2;
  console.info(obj,map,set);

  //
  console.info({
    map.has('t'),
    set.has(item),
    't' in obj
  })
}

Map最好用,Set唯一性较好

猜你喜欢

转载自www.cnblogs.com/sunmarvell/p/9134484.html