问题描述
我一直在关注这个 发布,但我无法让我的数组将数组中的所有数字相加.
I've been following this post but I cannot get my array to add up all numbers in my array.
我用这个:
var array_new = [$(".rightcell.emphasize").text().split('€')];
给我这个数组:
array_new: ,102.80,192.60,22.16
然后我这样做:
var sum = array_new.reduce((a, b) => a + b, 0);
console.log(sum); //gives me this 0,102.80,192.60,22.16
当我只想把数字加起来时,我得到了这个结果0,102.80,192.60,22.16.有人能给我建议吗?
When all I want to do is add up the numbers, I get this result 0,102.80,192.60,22.16. Can anyone advise me?
推荐答案
由于您的数组由 undefined
和一堆字符串组成,因此您必须解析这些值才能获得数字.答案是:
Since your array is composed of undefined
and a bunch of strings you have to parse the values to get the numbers. The answer would be:
var data = [,'102.80','192.60','22.16'];
console.log(data.reduce((r,c) => r + parseFloat(c), 0))
但是,如果您不想处理该函数中的解析,您可以确保您的数组以数字数组的形式出现:
However if you do not want to deal with the parsing in that function you can make sure that your array comes out as array of numbers like this:
Array.from([$(".rightcell.emphasize").text().split('€')], (x) => parseFloat(x || 0))
这将使您的数组准备好求和,而无需在 Array.reduce
中解析.所以它会是这样的:
Which would get your array ready for summation and without the need to parse inside the Array.reduce
. So it would be something like this:
var strings = [,'102.80','192.60','22.16'];
var numbers = Array.from(strings, (x) => parseFloat(x || 0))
console.log(numbers.reduce((r,c) => r + c, 0))
但在您的情况下,它会更短,因为您会将前两行作为第二行代码片段中的一行.
But in your case it would be shorter since you would do the first 2 lines as one as shown in the 2nd code snippet.
这篇关于将数组中的数字相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!