gpt4 book ai didi

javascript - 为什么 reduce 以这种方式工作?

转载 作者:行者123 更新时间:2023-11-29 10:40:53 25 4
gpt4 key购买 nike

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

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

但为什么在我的实现中 i 的第一个值是 1,从而砍掉了 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]}

最佳答案

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

当您进行直接求和时,不提供初始值很有用(例如),但对于这种这种事情,我发现最简单的方法是使用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

关于javascript - 为什么 reduce 以这种方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29565614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com