简体   繁体   English

JavaScript 是否有 Map 文字表示法?

[英]Does JavaScript have a Map literal notation?

As of ES6, JavaScript has a proper Map object. I don't see a way to use a literal notation though, as you could with an Array or an Object. Am I missing it, or does it not exist?从 ES6 开始,JavaScript 有一个正确的 Map object。不过我没有看到使用文字符号的方法,就像您可以使用数组或 Object 一样。我错过了它,还是它不存在?

Array: var arr = ["Foo", "Bar"];数组: var arr = ["Foo", "Bar"];

Object: var obj = { foo: "Foo", bar: "Bar" }; Object: var obj = { foo: "Foo", bar: "Bar" };

Map: ??? Map:???

No, ES6 does not have a literal notation for Map s or Set s. 不,ES6没有Map s或Set的文字符号。

You will have to use their constructors, passing an iterable (typically an array literal): 您将不得不使用它们的构造函数,传递一个iterable(通常是一个数组文字):

var map = new Map([["foo", "Foo"], ["bar", "Bar"], …]);

var set = new Set(["Foo", "Bar", …]);

There are some proposals to add new literal syntax to the language, but none made it into ES6 (and I'm personally not confident they will make it into any future version). 有一些建议要为语言添加新的文字语法,但没有一个提到ES6(我个人不相信他们会在未来的任何版本中使用它)。

It's like a HashMap -- there is no literal version. 它就像一个HashMap - 没有文字版本。 You have to define it like you would a constructor. 你必须像构造函数一样定义它。

You can read this topic which discusses map literals though, and why they should be added. 您可以阅读本主题 ,其中讨论了地图文字,以及为什么要添加它们。 It's basically others potential proposals on Map literals. 这基本上是其他关于Map文字的潜在提案。 I personally can't forsee a literal syntax in ES7, since Maps are very easy to use as is -- but in future proposals there could be syntactic sugar applied. 我个人不能预见ES7中的字面语法,因为地图很容易使用 - 但在将来的提案中可能会应用语法糖。

An example of potential literal notation was discussed using an octothorp (a hash) to look something like: 使用octothorp(散列)来讨论可能的文字符号的示例,如下所示:

const myMap = Map#{expression("derp"): value("herp")};

有一种方法可以做到这一点,就像我们使用文字一样

const fruits = new Map(Object.entries({apples: 1, bananas: 2}))

It's 2023 and map literal syntax is still not included in ECMAScript standard, though this NPM package called map-literal does exactly what you want.它是 2023 和 map 文字语法仍未包含在 ECMAScript 标准中,尽管这个名为map-literal 的NPM package 完全符合您的要求。

Object.entries() can make a Map object for you, but it cannot deal with nested structures. Object.entries()可以为你做一个Map object ,但是它不能处理嵌套结构。 Therefore you will need to use a package for that.因此,您需要为此使用 package。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM