Map和Object的基本操作
1. 键值区别
Map 默认情况下,Map不包含任何键。这是一个全新的开始
Object 默认情况下,有自己的原型,包含对象的基本方法
2. map和Object的迭代
2.1 Map迭代
for (const [key, value] of map) { console.log(`key: ${key}, value: ${value}`); } for (const key of map.keys()) { // or map.values() console.log(key); } //map支持forEach方法 map.forEach((value, key) => console.log(`key: ${key}, value: ${value}`));
2.2 Object迭代
for(let key in obj){ console.log(`key: ${key}, value: ${obj[key]}`) } Object.entries(obj).forEach((item) => console.log(`key: ${item[0]}, value: ${item[1]}`))
3. Map和Object与数组合并
3.1 Map与数组合并
//map转数组 Array.from(map) 或者 [...map] //数组转map let arr = [ [1, 'one'], [2, 'two'] ] new Map(arr) //map与数组合并 let map = new Map([ [1, 'one'], [2, 'two'] ]); let arr = [3, 'three'] let combinedMap = new Map(...map, arr); // { 1 => 'one', 2 => 'two', 3 => 'three' } let combinedArr = [...map, arr]; // [ [1, 'one'], [2, 'two'], [3, 'three'] ]
3.2 将对象合并到数组中
Array.from(Object.entries(obj)) 或 [...Object.entries(obj)]
3.3 Map与数组转换
let arr = ['one','two'] //数组转map new Map(arr.map((t,i) => [i,t])) //map转数组 Array.from(map) Array.from(map).map(t => t[1]) Array.from(map).map(t => t[0]) Array.from(map.values()) Array.from(map.keys()) [...map] [...map.values()] [...map.keys()]
4. Map实现数组去重
//map的key也是不允许重复的,如果初始化时有重复,会自动删除,map和set一样可以实现去重 const books = [ { id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' }, { id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' }, { id: 2, title: 'The Alchemist', author: 'Paulo Coelho' }, ] const uniqueObjsArr = [...new Map(books.map(book => [book.id, book])).values()]
5. Map的key是有序的,可以实现队列的效果