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              Value
    1   ---->      Gengi
    2   ---->      Harry
    3   ---->      Sam
    4   ---->      Jake
    5   ---->      Fuzzy
    And 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                  Value
    stud_19_1   ---->   Gengi
    stud_18_7   ---->   Harry
    stud_19_2   ---->   Sam
    stud_19_11  ---->   Jake
    stud_18_3   ---->   Fuzzy

Student 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.

现在假设我们要存储学生的年龄和姓名,并将学生的姓名映射到他们的年龄。 我们可以将年龄存储为键,将名称存储为值。 但是,大量的学生将具有相同的年龄。 这是映射中的约束,它与其他只能包含唯一键的数据结构有显着区别。 如果我们让HarrySam都只有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

输出量

 true

Since 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

输出量

false

A 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
false

In objects this becomes a bit more tedious,

在物体上,这变得更加乏味,

isExist='name' in obj1;
isExist='age' in obj1;

Output

输出量

true
false

To 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
2

You 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值