javascript
JavaScript中的地图与对象
JavaScript對象與地圖 (JavaScript Objects vs Maps)
Objects are super popular in JavaScript so it's not a term you are hearing for the first time even if you're a novice JS developer. Objects, in general, are a very common data structure that is used very often unlike maps. Maps are rarely ever used, you might think, however quite contrary to these maps are even more popular when it comes to building applications. In this article, we'll talk briefly about maps, what they are, how and where they are used? We'll then look at the maps in detail in JavaScript and then finally compare them with objects, which will be our main goal since both of them are quite similar.
對象在JavaScript中非常流行,因此即使您是JS新手,這也不是您第一次聽到的術語。 通常,對象是一種非常常見的數據結構,與地圖不同,它經常使用。 您可能會想,很少使用過地圖 ,但是,與這些地圖完全相反的是,在構建應用程序時更為流行。 在本文中,我們將簡要介紹一下地圖,它們是什么,如何使用它們以及在哪里使用? 然后,我們將詳細研究JavaScript中的地圖,然后將它們與對象進行比較,這是我們的主要目標,因為兩者非常相似。
Let's first understand what maps are, in general. The map is an abstract data structure that stores key-value pairs of any type where every key is unique. For example, let's say we have a list of students and their roll numbers starting from 1 till 50. We can store this data inside a map where our keys will be the roll numbers and the names of students as their corresponding values.
首先,讓我們首先了解什么是地圖。 該映射是一個抽象的數據結構,用于存儲每個鍵都是唯一的任何類型的鍵值對。 例如,假設我們有一個學生列表及其從1到50的開始編號。我們可以將此數據存儲在地圖中,其中我們的鍵將是開始編號以及作為相應值的學生姓名。
Key Value1 ----> Gengi2 ----> Harry3 ----> Sam4 ----> Jake5 ----> FuzzyAnd so on,You might say why not store this data inside a simple array and the index could act as the roll no? True, we can. Maps are very similar to arrays in the sense that our keys are mapped to a certain value. However, let's say we now want to map a student ID with a student name,
您可能會說為什么不將這些數據存儲在一個簡單的數組中,而索引卻可以作為roll no? 是的,我們可以。 在將我們的鍵映射到某個值的意義上,映射與數組非常相似。 但是,假設我們現在要映射一個帶有學生姓名的學生ID,
Key Valuestud_19_1 ----> Gengistud_18_7 ----> Harrystud_19_2 ----> Samstud_19_11 ----> Jakestud_18_3 ----> FuzzyStudent ID represents, say the roll number of a student along with the student's batch. This information can't be interpreted as an index since arrays will always have a numeric index. Here, we can use maps to store this data as our key is not an integer or a number but an alphanumeric or a string.
學生ID代表學生的卷號以及該學生的批次。 該信息不能解釋為索引,因為數組將始終具有數字索引。 在這里,我們可以使用映射來存儲此數據,因為我們的密鑰不是整數或數字,而是字母數字或字符串。
Let's suppose now that we want to store the age and names of students and map a student's name to their age. We can store age as the key and name as the value. However, a large number of students will have the same age. This is the constraint in maps which remarkably distinguishes it from other data structures that maps can only contain unique keys. If we have Harry and Sam both having the age of 14, we can either store 14 ---> Harry or 14 ----> Sam, not both. You might say we can take the names as key but then again, there could be two students with the same name having the same or different age.
現在假設我們要存儲學生的年齡和姓名,并將學生的姓名映射到他們的年齡。 我們可以將年齡存儲為鍵,將名稱存儲為值。 但是,大量的學生將具有相同的年齡。 這是映射中的約束,它與其他只能包含唯一鍵的數據結構有顯著區別。 如果我們讓Harry和Sam都只有14歲 ,那么我們可以存儲14 ---> Harry或14 ----> Sam,不能同時存儲兩者 。 您可能會說我們可以將姓名作為關鍵字,但是同樣地,可能會有兩個同名學生的年齡相同或不同。
So maps are used where we are sure that we need to store key-value pairs and every key is unique. Maps are built in a way to perform search operations faster as they take up a large amount of space to achieve this. This is why they are also referred to as hashmaps. An important use case would be the contacts in your smartphone. The reason why you can quickly search for a contact on the list is that they are probably implemented as a hashmap with name as the key and value as their phone number. You can have an array of values about a key too but the underlying principle is that you cannot save a different or the same number with a name that already exists in the contact list. A workaround would this would be a hashed string consisting of the contact name and the timestamp (the moment at which that contact was created) that way you can store duplicate names and still perform super fast search operations!
因此,在確保需要存儲鍵值對且每個鍵都是唯一的情況下使用了映射 。 構建地圖的方式可以更快地執行搜索操作,因為它們會占用大量空間來實現此目的。 這就是為什么它們也稱為哈希圖的原因。 一個重要的用例是智能手機中的聯系人。 您可以在列表中快速搜索聯系人的原因是,它們可能被實現為以名稱為鍵,值作為電話號碼的哈希圖。 您也可以具有有關鍵的值的數組,但是其基本原理是您不能使用聯系人列表中已經存在的名稱保存不同或相同的數字。 解決方法是使用由聯系人姓名和時間戳(創建聯系人的時間)組成的哈希字符串,這樣您就可以存儲重復的姓名并仍然執行超快速搜索操作!
Let's move to objects now. We know everything in JS is an object that belongs to the object class. So are maps. There's the first difference: Maps are an instance of objects however vice versa is not true.
讓我們現在移至對象。 我們知道JS中的所有內容都是屬于對象類的對象。 地圖也是如此。 第一個區別是:映射是對象的實例,但反之亦然 。
const myMap = new Map([[1, 'Gengi'],[2, 'Fuzzy'] ]); console.log(myMap instanceof Object);Output
輸出量
trueSince we're on it, this is how we create a new map in JS using the new keyword followed by the data structure name, much like we create objects using the new keyword and specify the key-value pairs inside the method.
既然在上面,這就是我們在JS中使用new關鍵字和數據結構名稱創建新地圖的方式 ,就像我們使用new關鍵字創建對象并在方法內部指定鍵值對一樣。
const myObj = new Object(); console.log(myObj instanceof Map);Output
輸出量
falseA stark difference between the two (now all our discussion would be specific to JS) is how we create them? Maps are fairly new and can only be created using the new keyword followed by the Map constructor method. However, you know that objects can be created in a number of ways.
兩者之間的明顯區別(現在我們所有的討論都將針對JS)是如何創建它們的? 地圖是相當新的,只能使用new關鍵字和Map構造函數方法創建。 但是,您知道可以通過多種方式創建對象。
const obj1 = {rollno: 23,name: 'John' } undefined const obj2 = new Object({rollno: 46,name: 'Chris' }) const obj3 = Object.create(null); console.log(obj1); console.log(obj2); console.log(obj3);Output
輸出量
{rollno: 23, name: "John"} {rollno: 46, name: "Chris"} {}The syntax in the map is more general and simple wrt objects when it comes to accessing elements and checking if they exist inside the data structure,
當涉及訪問元素并檢查元素是否存在于數據結構中時,映射中的語法更通用,更簡單。
myMap.get(1); obj1["name"];Output
輸出量
"Gengi" "John" myMap.has(1); myMap.has(46);Output
輸出量
true falseIn objects this becomes a bit more tedious,
在物體上,這變得更加乏味,
isExist='name' in obj1; isExist='age' in obj1;Output
輸出量
true falseTo add elements in a map,
要在地圖中添加元素,
myMap.set(46, 'John'); console.log(myMap);Output
輸出量
Map(3) {1 => "Gengi", 2 => "Fuzzy", 46 => "John"}Both maps and objects in a similar way perform the insert operation in O(1) time.
映射和對象均以O(1)時間執行插入操作。
delete obj2.rollno; myMap.delete(46); console.log(obj2); console.log(myMap);Output
輸出量
{name: "Chris"} Map(2) {1 => "Gengi", 2 => "Fuzzy"}Deleting single element is quite similar with both performing it in O(1) time, however, to remove all the elements from an object we'll have to traverse the object and delete all elements one by one, whereas we can directly do so using the clear() method in map,
刪除單個元素與兩者都在O(1)時間內執行非常相似 ,但是,要從對象中刪除所有元素,我們必須遍歷該對象并逐個刪除所有元素,而我們可以直接使用map中的clear()方法,
myMap.clear(); console.log(myMap);Output
輸出量
Map(0) {}Getting the size is also relatively easier in maps.
在地圖中獲取尺寸也相對容易。
console.log(myMap.size); console.log(Object.keys(obj1).length);Output
輸出量
0 2You might think maps have simpler syntax so why not use them everywhere? However, objects are more popular and have a direct reference with JSON. Plus storing duplicate items comes in handy when using an object. So it really depends on what your use case for the data structure is, both can do a pretty great job is used appropriately!
您可能會認為地圖的語法更簡單,為什么不在各處使用地圖呢? 但是,對象更受歡迎,并且具有JSON的直接引用。 使用對象時,加上存儲重復項非常方便。 因此,這實際上取決于您的數據結構用例,正確使用兩者都可以做得很好!
翻譯自: https://www.includehelp.com/code-snippets/maps-vs-objects-in-javascript.aspx
總結
以上是生活随笔為你收集整理的JavaScript中的地图与对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软牡丹多少钱一包啊?
- 下一篇: javascript 常量_JavaSc