一直以來,JavaScript使用數組和對象來定義和存放結構化數據, 在這篇文章中,我們將一起深挖另一種對象Map的一切,我們將會去了解它是什么、如何遍歷、都包括什么屬性和方法以及優缺點是什么。
介紹
JavaScript的Map對象數據結構類似於例如C#,Java或C ++中的字典,本質是一組包含鍵值對的集合,如果你了解其他語言的鍵/值對數據結構的概念的話,那么對您立即掌握Map基本概念是很有幫助的。不過,即便你之前沒有接觸過任何一種語言,那也不必擔心,我們會從基礎知識開始講起的。
在將Map引入JavaScript語言之前,Object是創建鍵/值對數據結構的主要方式。而Map與常規對象有什么區別?
主要有兩點不同:
1. key的類型無限制
Object無法使用非字符串值作為鍵名,但Map的鍵名可以是任意類型,讓我們來看一個例子。
1
2
3
4
|
var
firstInstance = { id: 1 };
var
secondInstance = { id: 2 };
console.log(firstInstance[
"id"
]);
console.log(secondInstance [
"id"
]);
|
輸出結果:1 2
下面我們將通過重新造輪子的形式讓你了解Map和上述例子有什么區別
1
2
3
4
5
6
7
|
var
firstInstance = { id: 1 };
var
secondInstance = { id: 2 };
var
sqlServer = {};
sqlServer[firstInstance] =
"SQLServer1"
;
sqlServer[secondInstance] =
"SQLServer2"
;
|
firstInstance和secondInstance這兩個對象都產生了“[Object Object]”。因此,將這兩個對象傳入sqlServer中作為其鍵名,就能使其達到類似Map的效果,以下是輸出結果。
在映射不同數據類型時,這個特性將提供極大的靈活性。
2. 可直接遍歷
常規對象里,為了遍歷keys、values和entries,你必須將它們轉換為數組,如使用Object.keys()、Object.values()和Object.entries(),或使用for ... in,另外for ... in循環還有一些限制:它僅僅遍歷可枚舉屬性、非Symbol屬性,並且遍歷的順序是任意的。
但Map可直接遍歷,且因為它是鍵值對集合,所以可直接使用for…of或forEach來遍歷。這點不同的優點是為你的程序帶來更高的執行效率。
什么是JavaScript Map?
從根上講,Map是鍵/值對的集合。這些鍵和值可以是任何數據類型。在ES6語法下, 創建JavaScript map對像非常簡單,讓我們看看例子
1
2
|
let
myMap =
new
Map();
console.log(myMap);
|
輸出結果:
如您所見,我們只是創建了一個空的Map對象而已,只需使用new Map(),就可以在JavaScript中直接創建新的Map。
如何初始化Map?
如何創建和初始化一個包含數據的map?
有多種方法可以對其進行初始化。讓我們一個接一個地看一看。
使用Array
1
2
3
4
5
6
7
8
9
|
let
topProgrammingLanguages =
new
Map([
[1,
'JavaScript'
],
[2,
'Python'
],
[3,
'Java'
],
[4,
'C#'
],
[5,
'C'
]
]);
console.log(topProgrammingLanguages);
|
輸出結果
使用set() 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
let
myFavoriteBooks =
new
Map();
myFavoriteBooks.set(1,
'Rich Dad Poor Dad'
);
myFavoriteBooks.set(2,
'The Magic of Thinking Big'
);
myFavoriteBooks.set(3,
'Think and Grow Rich'
);
myFavoriteBooks.set(4,
'How to Win Friends & Influence People'
);
myFavoriteBooks.set(5,
'Shoe Dog'
);
console.log(myFavoriteBooks);
|
輸出結果
使用get、has、includes、clear和delete方法
使用 get() 方法
該方法返回key對應的value,如果不存在,則返回undefined。
1
2
3
4
5
6
7
8
9
10
|
let
sqlServerInstances =
new
Map();
sqlServerInstances.set(
'SQL_DEV_Instance'
,
'MS_SQLSERVER_1'
);
sqlServerInstances.set(
'SQL_UAT_Instance'
,
'MS_SQLSERVER_2'
);
sqlServerInstances.set(
'SQL_PROD_Instance'
,
'MS_SQLSERVER_3'
);
console.log(sqlServerInstances.get(
"SQL_DEV_Instance"
));
//output: MS_SQLSERVER_1
console.log(sqlServerInstances.get(
'SQL_UAT_Instance'
));
//output: MS_SQLSERVER_2
console.log(sqlServerInstances.get(
"SQL_PROD_Instance"
));
//output: MS_SQLSERVER_3
console.log(sqlServerInstances.get(
"SQL "
));
//output: undefined
|
使用 has() 方法
該方法用於檢查Map是否有指定key對應的value。
1
2
3
4
5
6
7
8
|
let
sqlServerInstances =
new
Map();
sqlServerInstances.set(
'SQL_DEV_Instance'
,
'MS_SQLSERVER_1'
);
sqlServerInstances.set(
'SQL_UAT_Instance'
,
'MS_SQLSERVER_2'
);
sqlServerInstances.set(
'SQL_PROD_Instance'
,
'MS_SQLSERVER_3'
);
console.log(sqlServerInstances.has(
"SQL_PROD_Instance"
))
//output: true
console.log(sqlServerInstances.has(
"SQL_PROD2_Instance"
))
//output: false
|
使用 clear() 方法
該方法用於清空指定map對象中的所有內容。
1
2
3
4
5
6
7
8
9
10
|
let
products =
new
Map();
products.set(
"PRODUCT_001"
, { name:
"Product 1"
});
products.set(
"PRODUCT_002"
, { name:
"Product 2"
});
products.set(
"PRODUCT_003"
, { name:
"Product 3"
});
//let's get the size of the Map before invoking clear()
console.log(products.size);
//output: 3
products.clear();
//clears the Map-products
console.log(products.size);
//output: 0
|
使用 delete() 方法
該方法用於刪除map中指定key對應的一組key-value元素
1
2
3
4
5
6
7
8
9
10
11
|
let
sqlServerInstances =
new
Map();
sqlServerInstances.set(
'SQL_DEV_Instance'
,
'MS_SQLSERVER_1'
);
sqlServerInstances.set(
'SQL_UAT_Instance'
,
'MS_SQLSERVER_2'
);
sqlServerInstances.set(
'SQL_PROD_Instance'
,
'MS_SQLSERVER_3'
);
//let's delete the UAT instance
console.log(sqlServerInstances.get('SQL_UAT_Instance
')); //output: MS_SQLSERVER_2
console.log(sqlServerInstances.delete('
SQL_UAT_Instance
')); //deletes the key/value pair
console.log(sqlServerInstances.has('
SQL_UAT_Instance
')); //output: false
console.log(sqlServerInstances.get('
SQL_UAT_Instance'));
//output: undefined
|
Map遍歷的方式
在本節中,我們將了解如何遍歷Map。但是,在此之前,我們需要了解以下方法:keys、values和entries,這些方法將在我們開始使用for-of循環遍歷map對象時很有幫助。
首先,我們將創建一個map對象作為數據源
1
2
3
4
5
6
|
let
myFavoriteBooks =
new
Map();
myFavoriteBooks.set(1,
'Rich Dad Poor Dad'
);
myFavoriteBooks.set(2,
'The Magic of Thinking Big'
);
myFavoriteBooks.set(3,
'Think and Grow Rich'
);
myFavoriteBooks.set(4,
'How to Win Friends & Influence People'
);
myFavoriteBooks.set(5,
'Shoe Dog'
);
|
使用 keys() 方法
該方法返回Map對象中每個元素的key。尤其是你在只需要遍歷Map集合的鍵時,更是如此。
1
2
|
const myMap1 =
new
Map([[1,
'red'
], [2,
'blue'
]]);
console.log(myMap1.keys());
//output: { 1, 2 }
|
遍歷key
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
* Output
* 1
* 2
* 3
* 4
* 5
*/
for
(const key of myFavoriteBooks.keys()) {
console.log(key);
}
//end of iteration over the keys
|
使用 values() 方法
和keys方法對應,values方法返回的就是Map對象中的value集合。
1
2
|
const myMap2 =
new
Map([[
'Electronic Gadget'
,
'Smart Phone'
], [
'Input Devices'
,
'Mouse'
]]);
console.log(myMap2.values());
//output: {"Smart Phone", "Mouse"}
|
遍歷value
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
* Output
* Rich Dad Poor Dad
* The Magic of Thinking Big
* Think and Grow Rich
* How to Win Friends & Influence People
* Shoe Dog
*/
for
(const value of myFavoriteBooks.values()) {
console.log(value);
}
//end of iteration over the values
|
使用 entry() 方法
該方法返回Map集合中每個 [key,value] 元素的對象。
1
2
3
4
|
const myMap3 =
new
Map([[
'Samsung'
,
'Smart Phone'
],
[
'Colgate'
,
'Toothpaste'
], [
'Coke'
,
'Soda'
]]);
console.log(myMap3.entries());
//output: {"Samsung" => "Smart Phone",
//"Colgate" => "Toothpaste", "Coke" => "Soda"}
|
遍歷條目
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
* Output
* 1 "Rich Dad Poor Dad"
* 2 "The Magic of Thinking Big"
* 3 "Think and Grow Rich"
* 4 "How to Win Friends & Influence People"
* 5 "Shoe Dog"
*/
for
(const [key, value] of myFavoriteBooks.entries()) {
console.log(key, value);
}
//end of iteration over the entries
|
散布運算符遍歷Map
在文章的最后一部分,我們將了解通過使用散布運算符(...)輕松遍歷map對象,下面讓我們看一個例子吧!
1
2
3
4
5
|
let
fastFoods =
new
Map([[1,
'McDO'
], [2,
'Burger King'
], [3,
'KFC'
],
[4,
'Wendys'
], [5,
'Pizza Hut'
]]);
console.log(...fastFoods.keys());
console.log(...fastFoods.values());
|
大家可以自行執行一下上面這段程序,看看運行結果是什么。
總結
在本文中,我們討論了JavaScript Map對象集合。相信通過這篇文章,你已經對Map對象有了一定的了解了。在文末,展示了遍歷Map的另一種形式for-of和散布運算符(...)來遍歷集合。
如果有什么問題或補充,歡迎通過評論區留言告訴我。