我正在尝试使用 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)
}