打字稿:运算符'+'不能应用于类型 'number' 和 'boolean'



我有一个表示数字的字符串数组,我希望能够看到某个字符串在我的数组上重复了多少次:

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
);

然而,reduce函数中的操作给了我以下错误:

Operator '+' cannot be applied to types 'number' and 'boolean'.

我该如何应对?

尝试使用

const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + (currentValue === searchForValue ? 1 : 0),
0
);

现在,在创建布尔值之前,三元运算符返回一个数字。

为了保持代码相对相同,只添加了Number cast/构造函数。

const numbers = ['1', '2', '3', '4', '6', '2', '9', '5', '2', '4', '8'];
const searchForValue = '2';
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + Number(currentValue === searchForValue),
0
);

Typescript喜欢类型的一致性!在您的代码尝试将布尔结果添加到一个不可能的数字之前(例如1+false(。我们在这里所做的只是将布尔结果转换为一个数字。然而,我建议学习Alexander Mills答案中的三元运算是如何工作的。

尝试以下操作:

searchForValue ='2';
timesAppeared = 0
for (let index = 0; index < numbers.length; index++) {
if(searchForValue==numbers[index]){
timesAppeared=timesAppeared+1;
}
console.log(timesAppeared);
}

最新更新