[英]Typescript: Operator '+' cannot be applied to types 'number' and 'boolean'
I have an array of strings representing numbers, and I want to be able to see how many times a certain string repeats on my array:我有一个表示数字的字符串数组,我希望能够看到某个字符串在我的数组上重复了多少次:
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
);
However, the operation inside my reduce function gives me the following error:但是,我的 reduce function 里面的操作给了我以下错误:
Operator '+' cannot be applied to types 'number' and 'boolean'.
How can I tackle this?我该如何解决这个问题?
try this instead试试这个
const timesAppeared = numbers.reduce(
(previousValue, currentValue) => previousValue + (currentValue === searchForValue ? 1 : 0),
0
);
now the ternary operator returns a number, before you were creating a Boolean.现在三元运算符返回一个数字,在您创建 Boolean 之前。
Trying to keep the code relatively the same, just added the Number cast/constructor.试图保持代码相对相同,只是添加了 Number cast/constructor。
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 loves type consistency. Typescript 喜欢类型一致性。 Before your code was trying to add a boolean result to a number which isn't possible (eg 1 + false).
在您的代码尝试将 boolean 结果添加到一个不可能的数字之前(例如 1 + false)。 All we did here was convert that boolean result to a number.
我们在这里所做的只是将 boolean 结果转换为数字。 However I would recommend learning how the ternary operation in Alexander Mills' answer works.
但是,我建议学习 Alexander Mills 答案中的三元运算是如何工作的。
prueba lo siguiente普鲁巴罗西吉恩特
searchForValue ='2';
timesAppeared = 0
for (let index = 0; index < numbers.length; index++) {
if(searchForValue==numbers[index]){
timesAppeared=timesAppeared+1;
}
console.log(timesAppeared);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.