使用reduce()计算数组中值的实例后如何返回ES6 Map对象?

Tra*_* Su 5 javascript

我刚刚开始学习 JavaScript,这是我带回家考试的一部分,要求对我来说非常棘手。

我们有很多方法可以在 JS 中计算对象中值的实例,但在这里我必须通过调用reduce()并返回一个 ES6 映射对象来实现它。

这是要求:

/**
* Takes an array of items, and returns a Map with the
* frequencies (counts) of each item in the array.
*
* Must do this by using a single call to reduce.
*
* For example,
*  freqs([1, 2, 3, 2, 7, 2, 1]) returns Map {1 => 2, 2 => 3, 3 => 1, 7 => 1}
*  freqs("One fish two fish red fish blue fish".split(' '))
*  returns Map {"One" => 1, "fish" => 4, "two" => 1, "red" => 1, "blue" => 1}
*/
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

function freqs(items) {
  var map = new Map();
  return items.reduce(function(allkey, key) {
    if (map.has(key)) {
      var value = map.get(key);
      map.set(key, value++);
    } else {
      map.set(key, 1);
    }
    return map;
  }, {})
}
Run Code Online (Sandbox Code Playgroud)

我使用了调试器,发现 onmap.set(key, value++)map迭代时不会覆盖新值。为什么?

所以当我输入时C = [1,2,3,2,7,2,1];,输出总是这样的:

Map(4) {1 => 1, 2 => 1, 3 => 1, 7 => 1}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

nic*_*oga 5

您的代码的问题是返回添加之前a++的值:a1

var a = 1;
console.log(a++);
console.log(a);
Run Code Online (Sandbox Code Playgroud)

由于Map#set修改后返回地图,因此您可以像这样简化代码:

function freqs(items) {
  return items.reduce(
    (map, e) => map.set(e, (map.get(e) || 0) + 1),
    new Map()
  );
}
Run Code Online (Sandbox Code Playgroud)

Alternatively, you may use the somewhat obscure and rarely seen increment operator prefix, which also increments the variable, but returns the incremented new version of it:

var a = 1;
console.log(++a);
console.log(a);
Run Code Online (Sandbox Code Playgroud)