1. 程式人生 > >詳細瞭解JS Map,它和傳統物件有什麼區別?

詳細瞭解JS Map,它和傳統物件有什麼區別?

轉載請註明出處:葡萄城官網,葡萄城為開發者提供專業的開發工具、解決方案和服務,賦能開發者。
原文出處:https://www.codeproject.com/Articles/5278387/Understanding-Maps-in-JavaScript

 

一直以來,JavaScript使用陣列和物件來定義和存放結構化資料, 在這篇文章中,我們將一起深挖另一種物件Map的一切,我們將會去了解它是什麼、如何遍歷、都包括什麼屬性和方法以及優缺點是什麼。

介紹

JavaScript的Map物件資料結構類似於例如C#,Java或C ++中的字典,本質是一組包含鍵值對的集合,如果你瞭解其他語言的鍵/值對資料結構的概念的話,那麼對您立即掌握Map基本概念是很有幫助的。不過,即便你之前沒有接觸過任何一種語言,那也不必擔心,我們會從基礎知識開始講起的。

在將Map引入JavaScript語言之前,Object是建立鍵/值對資料結構的主要方式。而Map與常規物件有什麼區別?

主要有兩點不同:

1. key的型別無限制

Object無法使用非字串值作為鍵名,但Map的鍵名可以是任意型別,讓我們來看一個例子。

var firstInstance = { id: 1 };
var secondInstance = { id: 2 };
console.log(firstInstance["id"]);
console.log(secondInstance ["id"]);

輸出結果:1 2

下面我們將通過重新造輪子的形式讓你瞭解Map和上述例子有什麼區別  

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對像非常簡單,讓我們看看例子

let myMap = new Map();
console.log(myMap);

輸出結果:  

 

 

如您所見,我們只是建立了一個空的Map物件而已,只需使用new Map(),就可以在JavaScript中直接建立新的Map。

如何初始化Map?

如何建立和初始化一個包含資料的map?

有多種方法可以對其進行初始化。讓我們一個接一個地看一看。

使用Array

let topProgrammingLanguages = new Map([
    [1, 'JavaScript'],
    [2, 'Python'],
    [3, 'Java'],
    [4, 'C#'],
    [5, 'C']
]);

console.log(topProgrammingLanguages);

輸出結果

 

使用set() 方法

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。

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。  

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物件中的所有內容。  

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元素  

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物件作為資料來源

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集合的鍵時,更是如此。

const myMap1 = new Map([[1, 'red'], [2, 'blue']]);
console.log(myMap1.keys());     //output: { 1, 2 }

遍歷key

/**
 * 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集合。

const myMap2 = new Map([['Electronic Gadget', 'Smart Phone'], ['Input Devices', 'Mouse']]);
console.log(myMap2.values());   //output: {"Smart Phone", "Mouse"}

遍歷value  

/**
 * 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] 元素的物件。  

const myMap3 = new Map([['Samsung', 'Smart Phone'], 
               ['Colgate', 'Toothpaste'], ['Coke', 'Soda']]);
console.log(myMap3.entries());   //output: {"Samsung" => "Smart Phone", 
                                 //"Colgate" => "Toothpaste", "Coke" => "Soda"}

遍歷條目

/**
 * 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物件,下面讓我們看一個例子吧!

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和散佈運算子(...)來遍歷集合。

如果有什麼問題或補充,歡迎通過評論區留言告訴我。

&n