且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将数组中的数字相加

更新时间:2023-02-05 13:45:26

由于您的数组由 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.