Parsing numbers in a javascript array

Hi I have a string of numbers separated by commas "100,200,300,400,500" which I split into an array using the javascript split function:

var data = [];
data = dataString.split(",");

I am trying to parse the values โ€‹โ€‹of an array using parseFloat and then save them back to the array. Then I would like to add numbers to the array and save it as another "dataSum" variable.

I have the following code, but I cannot get it to work:

var dataSum = "";

for (var i=0; i < data.length; i++) {
    parseFloat(data[i]);
    dataSum += data[i];
}

So, at the end of all this, I should be able to access any of the parsed numbers separately for data [0], data [1], etc ... and have a total number for dataSum. What am I doing wrong?

+3
source share
3

(1)

var dataSum = "";

dataSum . += - , 100200300400500 - . 0:

var dataSum = 0;

(2)

parseFloat . float.

dataSum += parseFloat(data[i]);

(3)

var data = [];
data = dataString.split(",");

.

var data = dataString.split(",");

(BTW, ECMAScript 5 :

return "100,200,300,400,500".split(/,/).map(parseFloat).reduce(function(x,y){return x+y;})

)

+10

parseFloat , , dataSum .

var dataSum = 0;

for (var i=0; i < data.length; i++) {
    var current = parseFloat(data[i]);
    dataSum += current;
    // to save back onto array
    // data[i] = current;
}
+6

parseFloat, -.

wcschools:

parseFloat() .

Also, adding a number to the string will result in a concatenation of the results, so you should use dataSumup to 0 instead of default "".

var dataSum = 0.0;

for (var i=0; i < data.length; i++) {
    dataSum += parseFloat(data[i]);
}
+2
source

Source: https://habr.com/ru/post/1739899/


All Articles