.map() 一个 Javascript ES6 地图? [英] .map() a Javascript ES6 Map?

查看:31
本文介绍了.map() 一个 Javascript ES6 地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会怎么做?本能地,我想做:

How would you do this? Instinctively, I want to do:

var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);

// wishful, ignorant thinking
var newMap = myMap.map((key, value) => value + 1); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

我没有从关于新迭代协议的文档中收集到太多信息.

我知道 wu.js,但我正在运行 Babel 项目并且不想包含 Traceur目前似乎取决于.

I am aware of wu.js, but I'm running a Babel project and don't want to include Traceur, which it seems like it currently depends on.

我对如何提取 fitzgen/wu.js 在我自己的项目中做到了.

希望对我在这里遗漏的内容有一个清晰、简洁的解释.谢谢!

Would love a clear, concise explanation of what I'm missing here. Thanks!

ES6 地图文档,仅供参考

推荐答案

所以 .map 本身只提供一个你关心的值...也就是说,有几种方法可以解决这个问题:

So .map itself only offers one value you care about... That said, there are a few ways of tackling this:

// instantiation
const myMap = new Map([
  [ "A", 1 ],
  [ "B", 2 ]
]);

// what's built into Map for you
myMap.forEach( (val, key) => console.log(key, val) ); // "A 1", "B 2"

// what Array can do for you
Array.from( myMap ).map(([key, value]) => ({ key, value })); // [{key:"A", value: 1}, ... ]

// less awesome iteration
let entries = myMap.entries( );
for (let entry of entries) {
  console.log(entry);
}

注意,我在第二个例子中使用了很多新东西.........Array.from 接受任何可迭代对象(任何时候使用 [].slice.call( ),加上 Sets 和 Maps)并将其转换为数组... ...Maps,当强制为数组时,变成数组数组,其中el[0] === key &&el[1] === value;(基本上,与我在上面预填充示例 Map 的格式相同).

Note, I'm using a lot of new stuff in that second example... ...Array.from takes any iterable (any time you'd use [].slice.call( ), plus Sets and Maps) and turns it into an array... ...Maps, when coerced into an array, turn into an array of arrays, where el[0] === key && el[1] === value; (basically, in the same format that I prefilled my example Map with, above).

我在 lambda 的参数位置使用数组的解构,在为每个 el 返回一个对象之前,将这些数组点分配给值.

I'm using destructuring of the array in the argument position of the lambda, to assign those array spots to values, before returning an object for each el.

如果您在生产环境中使用 Babel,您将需要使用 Babel 的浏览器 polyfill(其中包括core-js"和 Facebook 的regenerator").
我很确定它包含 Array.from.

If you're using Babel, in production, you're going to need to use Babel's browser polyfill (which includes "core-js" and Facebook's "regenerator").
I'm quite certain it contains Array.from.

这篇关于.map() 一个 Javascript ES6 地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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