问题
Hi I have a string of numbers separated by commas, "100,200,300,400,500" that I'm splitting into an array using the javascript split function:
var data = [];
data = dataString.split(",");
I'm trying to parse the values of the array using parseFloat and then store them back into the array. I'd then like to add up the numbers in the array and store it as another variable, "dataSum".
I've got the following code, but I can't get it working:
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 individually data[0], data[1], etc... and have a total number for dataSum. What am I doing wrong?
回答1:
(1)
var dataSum = "";
You are initializing dataSum
as a string. For strings, the +=
is a concatenation operator, so you'll get 100200300400500
because of concatenation. You should initialize it to 0:
var dataSum = 0;
(2)
parseFloat
does not modify the input parameter. The float value is returned. So you should use
dataSum += parseFloat(data[i]);
(3)
var data = [];
data = dataString.split(",");
The 2nd assignment will override the 1st. Just write
var data = dataString.split(",");
(BTW, ECMAScript 5 supports this one-liner:
return "100,200,300,400,500".split(/,/).map(parseFloat).reduce(function(x,y){return x+y;})
)
回答2:
parseFloat returns a value, which you should use to make your calculation, also, you should initialize your dataSum variable to a numeric value.
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;
}
回答3:
You are using parseFloat
but not assigning the result to anything.
From wcschools:
The parseFloat() function parses a string and returns a floating point number.
Additionally, adding a number to a string will concatenate the results, so you should default your dataSum
to 0, not to ""
.
var dataSum = 0.0;
for (var i=0; i < data.length; i++) {
dataSum += parseFloat(data[i]);
}
来源:https://stackoverflow.com/questions/2580655/parsing-numbers-in-a-javascript-array