javascript 如何在 ES6/ES2015 中初始化类似于 Object 表达式的 Map?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32877552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:50:59  来源:igfitidea点击:

How to initialize a Map in ES6/ES2015 similar to an Object expression?

javascriptecmascript-6

提问by Dan Dascalescu

What is the equivalent of

相当于什么

var object = {
  'foo': 'bar',
  1: 42
}

using an ES6 Map?

使用 ES6地图

回答by Amit

The closest you can get is:

你能得到的最接近的是:

let object = new Map([
  ['foo', 'bar'],
  ['1', 42]
]);

Important things to notice:

需要注意的重要事项:

  1. Object properties are identified by strings, while Map keys can be any value, so make sure all keys are strings in the input array.
  2. Iterating a Map object yields entries by insertion order. That is not guaranteed for objects, so behavior might be different.
  1. 对象属性由字符串标识,而 Map 键可以是任何值,因此请确保所有键都是输入数组中的字符串。
  2. 迭代 Map 对象按插入顺序生成条目。对于对象,这不能保证,因此行为可能会有所不同。

回答by Dimitris

In modern browsers it can be as simple as:

在现代浏览器中,它可以很简单:

new Map(Object.entries(object))