如果有一件事我知道如何做好,那就是如何跟上变化。因为如果你不这样做,你就会落后。我亲身体会到,使用熟记在心的东西,而不是尝试“新的”东西,是多么舒服。
但不适是让你成长的原因,无论是作为普通人还是开发者。
让我们先深入看看“新”Map能教给我们什么。
以下是holy source (MDN)的定义:
Map对象保存着键值对,并记住键的原始插入顺序。任何值(包括对象和基本类型值)都可以用作键或值。
简单来说,Map是JavaScript原生的散列或字典数据结构。
Andrej发布了一个方便的备忘单,很好地展示了它们的语法差异。
Map
默认情况下,Map不包含任何键。这是一个全新的开始。它只有你放进去的东西。
不多也不少。
Object
默认情况下,对象都有自己的原型,因此它包含的默认键可能与你自己的键发生冲突。
在创建新对象时,可以通过传递null作为原型绕过该方法:
看看它们的区别:
Map
map接受任何类型的键。这包括函数、对象和所有基本类型(string、number、boolean、symbol、undefined、null和bigint)。
let obj = { 'a': 'a' };
let func = () => 'hey';
//也可以使用数组语法一次初始化多个值
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
//对象和函数是按引用存储的,所以{'a':'a'}和obj是不同的对象)
Object
对象的键必须是字符串或符号(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'] 转换所有的key为字符串
obj[func] //undefined
obj['func'] // 'function'
Map
map本身是可迭代的。这意味着可以使用for或。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
//如果你只想要` values `或者` 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
对象是不可迭代的,尽管可以使用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和数组是100%兼容的,可以直观地从一个映射到另一个。
下面展示了如何将Map转换为数组
let map = new Map([ [1, 'one'], [2, 'two'] ]);
Array.from(map) //[ [1, 'one'], [2, 'two'] ] 和你最初传入的数组一模一样
//或者你可以使用展开运算符
const newArr = [...map];
数组映射到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
将对象合并到数组中
let obj = { 1: 'one', 2: 'two'};
Array.from(obj) // []
//你必须这样
Array.from(Object.entries(obj))
//[ ['1', 'one'],['2', 'two'] ]
//或者
[...Object.entries(obj)]
//[ ['1', 'one'],['2', 'two'] ]
Map
Map有一个内置的size属性,可以返回其大小。
let map = new Map([1, 'one'], [true, 'true']);
map.size // 2
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()来序列化和解析JSON对象。
#1 计算电子商务购物车的总价格和商品
这是JavaScript .reduce()函数完整指南中的一个例子
给定下面的数组
const shoppintCart = [
{ price: 10, amount: 1 },
{ price: 15, amount: 3 },
{ price: 20, amount: 2 },
]
我们希望返回一个类似{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 } //初始化对象
)
// { 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 }
#2 从数组中删除重复对象的另一种方法
这是我在开始学习JavaScript时在制作bookshelf应用程序时用到的一段代码。
通过搜索如何从数组中删除重复对象,我找到了下面分享的示例。
这是一个包含一个重复对象的数组
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. 将数组映射为一个包含`id`和`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.由于键必须是唯一的,重复的键会被自动删除
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. 将这些值转换回数组。
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。
如果你只使用基于字符串的键,并且需要最大的读取性能,那么对象可能是更好的选择。
除此之外,用你想用的任何东西,因为,在一天结束的时候,这只是一个在互联网上随便一个人的文章。
以下是我们介绍的内容:
感谢您的阅读!
页面更新:2024-03-15
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号