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

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

问题描述

参考:MDN地图


当关键字不明,直到运行时,并且
所有键都是相同的类型,所有的值都是相同的类型时,使用映射到对象上。



当有逻辑操作单个元素时,使用对象。




问题:



使用Maps over对象的适用示例是什么?特别是运行时什么时候不知道密钥?

  var myMap = new Map(); 

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

//设置值
myMap.set(keyString,与字符串关联的值);
myMap.set(keyObj,与keyObj关联的值);
myMap.set(keyFunc,与keyFunc关联的值);

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


解决方案


什么是适用的使用Maps over对象的示例?


我认为你已经给了一个很好的例子:你至少需要使用映射 s当您使用对象(包括功能对象)作为键。


什么时候钥匙在运行时间是未知的?


无论何时在编译时不知道。总之,当您需要键值 c>时,您应始终使用 EM>集合 。您需要集合的一个很好的指标是当您从集合中动态添加和删除值时,尤其是当您不预先知道这些值(例如,从数据库读取,由用户输入等)时, / p>

相比之下,当您知道在编写代码时对象具有多少属性 - 当其形状为静态时,应使用对象。正如@Felix所说:当你需要一个记录时。需要的一个很好的指标是当字段有不同的类型时,以及当您不需要使用括号符号(或期望其中的一组有限的属性名称)时。


Ref: MDN Maps

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.

Question:

What is an applicable example of using Maps over objects? in particular, "when would keys be unknown until runtime?"

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?

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?"

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

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

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

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