Dan*_*ona 0 javascript typescript
我有一个代表数字的字符串数组,我希望能够查看某个字符串在我的数组中重复了多少次:
const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2'. '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + (currentValue === searchForValue),
0
);
Run Code Online (Sandbox Code Playgroud)
然而,我的reduce函数内部的操作给出了以下错误:
Operator '+' cannot be applied to types 'number' and 'boolean'.
我该如何解决这个问题?
试试这个
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + (currentValue === searchForValue ? 1 : 0),
0
);
Run Code Online (Sandbox Code Playgroud)
现在,在创建布尔值之前,三元运算符返回一个数字。
| 归档时间: |
|
| 查看次数: |
234 次 |
| 最近记录: |