.map() Javascript ES6 地图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31084619/
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-08-23 06:10:56  来源:igfitidea点击:

.map() a Javascript ES6 Map?

javascriptecmascript-6

提问by neezer

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 }

I've haven't gleaned much from the documentation on the new iteration protocol.

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

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

我知道wu.js,但我正在运行一个Babel项目并且不想包含Traceur它似乎目前依赖于.

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

对于如何将fitzgen/wu.js如何提取到我自己的项目中,我也有点无能为力。

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

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



Docs for ES6 Map, FYI

ES6 Map 文档,仅供参考

采纳答案by Norguard

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

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

// 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);
}

Note, I'm using a lot of new stuff in that second example... ...Array.fromtakes 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).

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

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.

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

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.

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

回答by Walter Chapilliquen - wZVanG

You should just use Spread operator:

您应该只使用Spread 运算符

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

var newArr = [...myMap].map(value => value[1] + 1);
console.log(newArr); //[2, 3, 4]

var newArr2 = [for(value of myMap) value = value[1] + 1];
console.log(newArr2); //[2, 3, 4]

回答by loganfsmyth

Just use Array.from(iterable, [mapFn]).

只需使用Array.from(iterable, [mapFn]).

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

var newArr = Array.from(myMap.values(), value => value + 1);

回答by saul.shanabrook

Using Array.fromI wrote a Typescript function that maps the values:

使用Array.from我编写了一个映射值的 Typescript 函数:

function mapKeys<T, V, U>(m: Map<T, V>, fn: (this: void, v: V) => U): Map<T, U> {
  function transformPair([k, v]: [T, V]): [T, U] {
    return [k, fn(v)]
  }
  return new Map(Array.from(m.entries(), transformPair));
}

const m = new Map([[1, 2], [3, 4]]);
console.log(mapKeys(m, i => i + 1));
// Map { 1 => 3, 3 => 5 }

回答by mayid

Actually you can still have a Mapwith the original keys after converting to array with Array.from. That's possible by returning an array, where the first item is the key, and the second is the transformed value.

实际上Map,在使用Array.from. 这可以通过返回一个数组来实现,其中第一项是key,第二项是转换后的value

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

const arrayMap = Array.from(originalMap, ([key, value]) => {
    return [key, value + 1]; // return an array
});

const alteredMap = new Map(arrayMap);

console.log(originalMap); // Map { 'thing1' => 1, 'thing2' => 2, 'thing3' => 3 }
console.log(alteredMap);  // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }

If you don't return that keyas the first array item, you loose your Mapkeys.

如果您不将该作为第一个数组项返回,则会丢失您的Map键。

回答by Hunter Liu

You can use myMap.forEach, and in each loop, using map.set to change value.

您可以使用 myMap.forEach,并在每个循环中使用 map.set 更改值。

myMap = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

for (var [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value);
}


myMap.forEach((value, key, map) => {
  map.set(key, value+1)
})

for (var [key, value] of myMap.entries()) {
  console.log(key + ' = ' + value);
}

回答by Yukulélé

You can use this function:

您可以使用此功能:

function mapMap(map, fn) {
  return new Map(Array.from(map, ([key, value]) => [key, fn(value, key, map)]));
}

usage:

用法:

var map1 = new Map([["A", 2], ["B", 3], ["C", 4]]);

var map2 = mapMap(map1, v => v * v);

console.log(map1, map2);
/*
Map { A → 2, B → 3, C → 4 }
Map { A → 4, B → 9, C → 16 }
*/

回答by mpen

If you don't want to convert the entire Map into an array beforehand, and/or destructure key-value arrays, you can use this silly function:

如果您不想事先将整个 Map 转换为数组,和/或解构键值数组,则可以使用这个愚蠢的函数:

/**
 * Map over an ES6 Map.
 *
 * @param {Map} map
 * @param {Function} cb Callback. Receives two arguments: key, value.
 * @returns {Array}
 */
function mapMap(map, cb) {
  let out = new Array(map.size);
  let i = 0;
  map.forEach((val, key) => {
    out[i++] = cb(key, val);
  });
  return out;
}

let map = new Map([
  ["a", 1],
  ["b", 2],
  ["c", 3]
]);

console.log(
  mapMap(map, (k, v) => `${k}-${v}`).join(', ')
); // a-1, b-2, c-3

回答by Commi

Map.prototype.map = function(callback) {
  const output = new Map()
  this.forEach((element, key)=>{
    output.set(key, callback(element, key))
  })
  return output
}

const myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]])
// no longer wishful thinking
const newMap = myMap.map((value, key) => value + 1)
console.info(myMap, newMap)

Depends on your religious fervor in avoiding editing prototypes, but, I find this lets me keep it intuitive.

取决于您避免编辑原型的宗教热情,但是,我发现这可以让我保持直观。

回答by Nils R?sel

I prefer to extend the map

我更喜欢扩展地图

export class UtilMap extends Map {  
  constructor(...args) { super(args); }  
  public map(supplier) {
      const mapped = new UtilMap();
      this.forEach(((value, key) => mapped.set(key, supplier(value, key)) ));
      return mapped;
  };
}