对比分析 Map 和 Object 的性能差异和应用场景,明确在高频键值操作中 Map 的优势。
我开始翻译这篇文章,保留所有代码块、术语和结构。
在 18 岁时,我以 IT 支持人员的身份开始了我的"职业生涯"。在 20 岁时,我每个月要飞行 80 小时担任空乘。在 22 岁时,我获得了商业飞行执照。在 29 岁时,我是一名木工,而如今 32 岁的我是一名软件开发人员。
有一件事我做得很好,那就是如何跟上变化的步伐。因为如果你不这样做,你就会被甩在后面。我深知用你已经熟悉的东西是多么舒服,而不愿意去尝试"新"的东西。
但不适感正是让你成长的东西,无论是作为一个人还是作为一名开发者。
让我们一头扎进去,看看这个"相对新颖的" Map 今天能教我们什么。
以下是权威来源(MDN)的定义:
Map 对象保存键值对,并且会记住键的原始插入顺序。任何值(包括对象和原始值)都可以用作键或值。
简单来说,Map 是 JavaScript 原生的哈希表或字典数据结构。
这是一份方便的速查表,很好地展示了它们的语法差异,由 Andrej 在 Twitter 上发布。
他还录制了性能测试,如果你感兴趣可以查看。
Map 默认情况下,Map 不包含任何键。它是一张白纸。它只有你放入其中的内容。
不多不少。
Object Object 默认有它们的原型,所以它包含默认键,这些键可能与你自己的键产生冲突。
这可以通过在创建新 Object 时将 null 作为原型来绕过:Object.create(null)
查看差异:
New Object with null prototype
Map Map 接受任何类型的键。这包括函数、对象和所有原始类型(string、number、boolean、symbol、undefined、null 和 bigint)。
let obj = { 'a': 'a' };
let func = () => 'hey';
//you can also initialize multiple values at once using array syntax
let map = new Map([[123, true], [true, 123], [obj, 'object'], [func, 'function']])
map.keys() // 123, true, Object, () => 'hey'
map.get(obj) // 'object'
map.get(func) // 'function'
map.get({ 'a': 'a' }) // undefined
//Object and Functions are stored by reference, so { 'a':'a' } and obj are different objects)
Object Object 的键必须是 String 或 Symbol。
let obj1 = { 'a': 'a' };
let func = () => 'hey';
let obj = { 123: true, true: 123, obj1: 'object', func: 'function' };
Object.keys(obj)
// ['123', 'true', 'obj1', 'func'] converts all keys to strings
obj[func] //undefined
obj['func'] // 'function'
Map Map 原生是可迭代的。这意味着你可以用 for of 或 .forEach() 循环遍历它们。
const map = new Map();
map.set(0, 'zero').set(1, 'one'); //you can chain .set()
for (const [key, value] of map) {
console.log(`key: ${key}, value: ${value}`);
}
// key: 0, value: zero
// key: 1, value: one
//if you just want the 'values' or just the 'keys'
for (const key of map.keys()) { // or map.values()
console.log(key);
}
// 0
// 1
map.forEach((value, key) => console.log(`key: ${key}, value: ${value}`));
// key: 0, value: zero
// key: 1, value: one
Object Object 不是可迭代的,尽管你可以使用 for in 和 Object.Entries() 来遍历它们。
let obj = { 0: 'zero', 1: 'one' }
for(let key in obj){
console.log(`key: ${key}, value: ${obj[key]}`)
}
// key: 0, value: zero
// key: 1, value: one
Object.entries(obj).forEach((item) => console.log(`key: ${item[0]}, value: ${item[1]}`))
// key: 0, value: zero
// key: 1, value: one
Map Map 和 Array 100% 兼容,使得从一个转换到另一个直观易行。
下面是如何将 Map 转换为 Array
let map = new Map([ [1, 'one'], [2, 'two'] ]);
Array.from(map) //[ [1, 'one'], [2, 'two'] ] exactly the same array you initially passed in
//or you can use the spread operator
const newArr = [...map];
let arr = [ [1, 'one'], [2, 'two'] ];
new Map(arr); //{ 1 => 'one', 2 => 'two' }
下面是如何合并 Map 和 Array
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'] ]
Object 将 Object 转换为 Array
let obj = { 1: 'one', 2: 'two'};
Array.from(obj) // [] doesn't work
//you'd have to do
Array.from(Object.entries(obj))
//[ ['1', 'one'],['2', 'two'] ]
//or
[...Object.entries(obj)]
//[ ['1', 'one'],['2', 'two'] ]
Map Map 有一个内置的 size 属性,返回其大小。
let map = new Map([1, 'one'], [true, 'true']);
map.size // 2
Object 要检查 object 的大小,你必须将 Object.keys() 与 .length 组合
let obj = { 1: 'one', true: 'true' };
Object.keys(obj).length // 2
Map Map 没有原生支持序列化或将其与 JSON 互转。
文档建议通过使用可以传递给 JSON.stringify(obj, replacer) 的 replacer 参数和传递给 JSON.parse(string, reviver) 的 reviver 参数来实现你自己的方法。
你可以在这里找到建议的实现
Object 你可以使用 JSON.stringify() 和 JSON.parse() 分别原生地将 Object 序列化和解析与 JSON 互转。
这是《JavaScript .reduce() 函数完全指南》中的一个例子
给定以下数组
const shoppintCart = [
{ price: 10, amount: 1 },
{ price: 15, amount: 3 },
{ price: 20, amount: 2 },
]
我们想返回一个 Object,如 { totalItems: 6, totalPrice: 45 }
这是原始代码
shoppintCart.reduce(
(accumulator, currentItem) => {
return {
totalItems: accumulator.totalItems + currentItem.amount,
totalPrice:
accumulator.totalPrice + currentItem.amount * currentItem.price,
}
},
{ totalItems: 0, totalPrice: 0 } //initial value object
)
// { totalItems: 6, totalPrice: 45 }
这是使用 Map 的版本
shoppintCart.reduce(
(accumulator, currentItem) => {
accumulator.set('totalItems', accumulator.get('totalItems') + currentItem.amount);
accumulator.set('totalPrice', accumulator.get('totalPrice') + currentItem.price);
return accumulator;
},
new Map([['totalItems', 0], ['totalPrice', 0]])
)
// { 'totalItems' => 6, 'totalPrice' => 45 }
这是我在刚开始学习 JavaScript 时制作的书架应用中实际使用过的代码片段。
搜索如何从数组中移除重复对象时,我找到了下面分享的例子。
这是一个包含一个重复对象的数组
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()
];
上面这一行中发生了太多事情。让我们将其分解成块,以便易于理解。
// 1. map the array into an array of arrays with `id` and `book`
const arrayOfArrays = books.map(book => [ book.id, book ])
// arrayOfArrays:
/*
[
[ 1, {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' } ],
[ 1, {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie' } ],
[ 2, { title: 'Alchemist', author: 'Paulo Coelho' } ]
]
*/
// 2. The duplicate is automatically removed as keys have to be unique
const mapOfUniqueObjects = new Map(arrayOfArrays)
// mapOfUniqueObjects:
/*
{
1 => {id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie'},
2 => { title: 'Alchemist', author: 'Paulo Coelho' }
}
*/
// 3. Convert the values back into an array.
const finalResult = [...mapOfUniqueObjects.values()];
// finalResult:
/*
[
{id: 1, title: 'How To Win Friends And Influence People', author: 'Dale Carnegie'},
{id: 2, title: 'The Alchemist', author: 'Paulo Coelho'}
]
*/
如果你需要存储键值对(哈希表或字典),使用 Map。
如果你仅使用基于字符串的键并需要最大读性能,那么 object 可能是更好的选择。
除此之外,使用你想要的任何东西,因为说到底,这只是互联网上某个随机家伙的博客文章而已哈哈。
这是我们涵盖的内容:
Map 对象是什么?
语法:Map vs Object
理由 1:你不会意外覆盖默认键
理由 2:它接受任何类型作为键
理由 3:Map 是可迭代的
理由 4:Map 可与数组合并,并可转换为数组
理由 5:你可以轻易检查大小
缺点?没有原生的序列化和解析方法
2 个用 Map 替代 Object 的例子
如果你喜欢这篇文章:
*在下面留言(你可以就说声 hi!)*在 Twitter @theguspear 上关注我
如需进一步操作,你可以考虑屏蔽此人和/或举报滥用行为