JavaScript 是否有一个 Map 字面符号?

在 ES6中,JavaScript 有一个合适的 Map 对象。但是,我没有看到使用文字符号的方法,就像使用 Array 或 Object 一样。是我错过了,还是根本不存在?

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

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

地图显示?

25368 次浏览

No, ES6 does not have a literal notation for Maps or Sets.

You will have to use their constructors, passing an iterable (typically an array literal):

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

It's like a HashMap -- there is no literal version. 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. 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.

An example of potential literal notation was discussed using an octothorp (a hash) to look something like:

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

There is a way to do it, like we do with literals

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