-2

我正在尝试使用 Array.reduce 复制以下函数

private getCount = (str, value) => {
var count = 0;
const everything = ['Key1', 'Key2', 'Key3', 'Key4', 'Key5'];
for (let i = 0; i < everything.length; i++) {
  if (everything === value) {
    count++;
  }
}

return count;}

这是我的尝试。但是,它仅在值为 时才给出正确的输出Key1。你能建议我可能出什么问题吗?

private getCount = (str, value) => {
  const everything = ['Key1', 'Key2', 'Key3', 'Key4', 'Key5'];
  return everything.reduce((accumulator, currentValue, currentIndex, array) => {
    return (currentValue === value ? accumulator + 1 : accumulator)
  }, 0)
}
4

1 回答 1

0

我质疑你为什么这么想用 reduce 来做这件事,但下面应该可以完成工作。

everything.reduce((ac, current)=> ac + (current === value ? 1 : 0), 0 );
于 2020-06-09T03:48:36.413 回答