ES6 中的地图与对象,何时使用? [英] Maps vs Objects in ES6, When to use?

查看:21
本文介绍了ES6 中的地图与对象,何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考:MDN 地图

当键在运行时之前未知时,以及当所有的键都是相同的类型,所有的值都是相同的类型.

Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type.

当存在对单个元素进行操作的逻辑时使用对象.

Use objects when there is logic that operates on individual elements.

问题:

在对象上使用地图的适用示例是什么?特别是,在运行之前什么时候密钥是未知的?"

var myMap = new Map();

var keyObj = {},
    keyFunc = function () { return 'hey'},
    keyString = "a string";

// setting the values
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");

console.log(myMap.get(keyFunc));

推荐答案

在对象上使用地图的适用示例是什么?

What is an applicable example of using Maps over objects?

我想你已经给出了一个很好的例子:当你使用对象(包括函数对象)作为键时,你至少需要使用 Maps.

I think you've given one good example already: You at least need to use Maps when you are using objects (including Function objects) as keys.

特别是在运行之前什么时候密钥是未知的?"

in particular, "when would keys be unknown until runtime?"

当它们在编译时未知时.简而言之,当您需要键值集合Map>.您需要集合的一个很好的指标是,当您从集合中动态添加和删除值时,尤其是当您事先不知道这些值时(例如,它们是从数据库中读取的,由用户输入等).

Whenever they are not known at compile time. In short, you should always use a Map when you need a key-value collection. A good indicator that you need a collection is when you add and remove values dynamically from the collection, and especially when you don't know those values beforehand (e.g. they're read from a database, input by the user, etc).

相反,当您在编写代码时知道对象具有哪些属性和多少属性时,您应该使用对象 - 当它们的形状是静态的.正如@Felix 所说:当您需要记录时.当字段具有不同类型时,以及何时不需要使用括号表示法(或期望其中包含一组有限的属性名称)时,需要这样做的一个很好的指标是.

In contrast, you should be using objects when you know which and how many properties the object has while writing the code - when their shape is static. As @Felix has put it: when you need a record. A good indicator for needing that is when the fields have different types, and when you never need to use bracket notation (or expect a limited set of property names in it).

这篇关于ES6 中的地图与对象,何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆