Home >Web Front-end >JS Tutorial >Comparison of map-set, arrays and objects in ES6 learning
Here is a brief comparison between them
It is mainly explained in the four aspects of adding, deleting, modifying and checking. For details, see the code
## 1. Comparison between map and array
{ // 数据结构横向对比,增,查,改,删 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. Comparison between set and array
{ // set和array的对比 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. Comparison of map, set and Object
{ // 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); }
Through comparison, it can be found that those who can use map should be used first instead of arrays.
Considering the uniqueness of data, consider using set instead of Objet
In future development, map and set can be given priority, and arrays and objects can be abandoned.
The above is the detailed content of Comparison of map-set, arrays and objects in ES6 learning. For more information, please follow other related articles on the PHP Chinese website!