Javascript Map对象如何改进我们的编码? [英] How will Javascript Map object improve our coding?

查看:73
本文介绍了Javascript Map对象如何改进我们的编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们可以使用javascript对象创建键/值对,那么什么是用于ES6新的Map()对象?

If we can make key/value pairs with javascript Objects, then what is suppose to be the use for the ES6 new Map() object?

什么时候应该使用一个和另一个?地图是否限于值或还可以包含函数?

When should I use one and when the other? Is Map limited to values or can it contain functions as well?

推荐答案


  1. 任何东西都可以用作

  2. 地图是有序的,可以进行迭代。

结合1和2,当您迭代地图时,您将获得一组有用的键值对!

Combining 1 and 2, when you iterate over a map, you'll get a useful array of key-value pairs!

查看 map.prototype.forEach()文档

资料来源:另一个好问题/答案交换

Source: Another good question/answer exchange. Worth marking this one as a duplicate.

更新:
添加到此答案以解决问题直接:

每当需要将事物联系在一起或保留插入顺序(通用数据结构需要)时,您应该使用地图。

Update: Adding to this answer to address the question directly:
You should use a map whenever you need to associate things together or preserve insertion order (common data structures need this).

当您不需要这样做时,您可以使用对象,但他们只是做不同的事情。

You can use an object when you don't need to do this, but they just do different things.

更新2:
OP询问函数是否也可以。是的,因为值也可以是函数!检查出来:

Update 2: OP asked if functions are okay too. Yes, because values can be functions too! Check it out:

let x = new Map();
let y = () => {
  console.log('derp');
}
x.set(y, "HI");
console.log(x.get(y)); //will log "HI"

有关更多信息,请查看此报价的来源, Eloquent JavaScript 的伟大篇章:

每个值都有一个类型JavaScript中有六种基本类型的值:数字,字符串,布尔值,对象,函数和未定义的值。

For more info, check out the source of this quote, in a great chapter of Eloquent JavaScript:
"Every value has a type that determines its role. There are six basic types of values in JavaScript: numbers, strings, Booleans, objects, functions, and undefined values."

另外,地图和对象之间的主要区别,从 MDN ,标题对象和地图比较

Also, the main differences between Map and Object, from MDN, under the header "Objects and Maps Compared":


  1. 一个对象有一个原型,所以地图中有默认键。但是,可以使用map = Object.create(null)绕过此操作。

  2. 对象的键是字符串,它们可以是Map的任何值。

  3. 您可以轻松获取地图的大小,同时必须手动跟踪对象的大小。

再次,密钥可以是任何值

这篇关于Javascript Map对象如何改进我们的编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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