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

查看:93
本文介绍了.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这样做提取到我自己的项目。

I also am a bit clueless as to how to extract how fitzgen/wu.js did it into my own project.

想要清楚,简明扼要地解释我在这里失踪的情况。谢谢!

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

ES6 Map的文档,FYI

推荐答案

所以 .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() / code>,加上集合和地图),并将其转换为数组... ...当强制转换为数组时,地图变为数组数组,其中 el [0] ===键&&& 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).

I '使用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的再生器)。

我确定它包含 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天全站免登陆