ES6學習筆記之map、set與數組、對象的對比,es6學習筆記

來源:互聯網
上載者:User

ES6學習筆記之map、set與數組、對象的對比,es6學習筆記

前言

ES5中的資料結構,主要是用Array和Object。在ES6中主要新增了Set和Map資料結構。到目前為止,常用的資料結構有四種Array、Object、Set、Map。下面話不多說了,來一起看看詳細的介紹吧。

// 資料結構橫向對比,增,查,改,刪

1、map和數組對比

{  let map=new Map(); let array=[]; /**增**/ map.set('t',1); array.push({t:1}); console.info('map-array',map,array);  /**查**/ let map_exist=map.has('t'); let array_exist=array.find(item=>item.t); console.info('map-array',map_exist,array_exist);  /**改**/ map.set('t',2); array.forEach(item=>item.t?item.t=2:''); console.info('map-array-modify',map,array);  /**刪**/ map.delete('t'); let index=array.findIndex(item=>item.t); array.splice(index,1); console.info('map-array-empty',map,array);}

2、set和數組對比

{ let set=new Set(); let array=[];   // 增 set.add({t:1}); array.push({t:1}); console.info('set-array',set,array); // 查 let set_exist=set.has({t:1}); let array_exist=array.find(item=>item.t); console.info('set-array',set_exist,array_exist);  // 改 set.forEach(item=>item.t?item.t=2:''); array.forEach(item=>item.t?item.t=2:''); console.info('set-array-modify',set,array);   // 刪 set.forEach(item=>item.t?set.delete(item):''); let index=array.findIndex(item=>item.t); array.splice(index,1); console.info('set-array-empty',set,array);}

3、map、set和Object對比

{  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('map-set-obj',obj,map,set);  // 查  console.info({ map_exist:map.has('t'), set_exist:set.has(item), obj_exist:'t' in obj })  // 改 map.set('t',2); item.t=2; obj['t']=2; console.info('map-set-obj-modify',obj,map,set);  // 刪除 map.delete('t'); set.delete(item);  delete obj['t']; console.info('map-set-obj-empty',obj,map,set);}

 通過對比可以發現,能使用map的優先使用,不使用數組,

 考慮資料的唯一性,考慮使用set,不使用Objet

 以後的開發中可以優先考慮使用map和set了,並且可以放棄數組和object了

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.