【问题标题】:Why is reduce working this way?为什么减少以这种方式工作?
【发布时间】:2015-04-11 00:17:54
【问题描述】:

我写了一个函数来满足以下条件:

“编写一个函数,给定一个字符串,生成所有字符索引的映射。例如, index("Mississippi") 应返回将“M”与集合 {0}、“i”与集合 {1、4、7、10} 相关联的地图,以及 等等。”

但是为什么i1在我的实现中的第一个值,从而切断了M

var s = 'Mississippi';

function indexes(s) {
  var acc = {};

  return s.split('').reduce(function(p, c, i) {
    if (!acc[c]) {
      acc[c] = [i];
    } else {
      acc[c].push(i);
    }

    return acc
  });
}
console.log(indexes(s)); // Object {i: Array[4], s: Array[4], p: Array[2]}

【问题讨论】:

  • i = 1 因为:“第一次调用回调时,previousValue 和 currentValue 可以是两个值之一。如果在调用 reduce 时提供了 initialValue,那么 previousValue 将等于 initialValue currentValue 将等于数组中的第一个值。如果没有提供 initialValue,则 previousValue 将等于数组中的第一个值,currentValue 将等于第二个。"跨度>

标签: javascript reduce


【解决方案1】:

因为您没有为累加器指定初始值,所以对回调的第一次调用在数组中具有前 两个 条目(例如,p 将是 "M"c 将是"i"),但你没有使用p,所以你最终错过了"M"

当您进行直接求和(例如)时,不提供初始值很有用,但对于 this 之类的事情,我发现使用 reduce 提供的最简单方法初始值,像这样:

var s = 'Mississippi';

function indexes(s) {
  // Note: No `acc` here
  return s.split('').reduce(function(p, c, i) {
    // Note: Using `p` here
    if (!p[c]) {
      p[c] = [i];
    } else {
      p[c].push(i);
    }

    return p;
  }, {});
  // ^^-- Initializing the accumulator here
}
snippet.log(JSON.stringify(indexes(s))); // {"M":[0],"i":[1,4,7,10],"s":[2,3,5,6],"p":[8,9]}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

如果您更愿意继续使用外部acc,我可能会使用forEach 而不是reduce

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多