在JavaScript解析数组数 [英] parsing numbers in a javascript array

查看:130
本文介绍了在JavaScript解析数组数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以逗号分隔的一串数字,100,200,300,400,500我使用的JavaScript split功能分成数组:

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(",");

我试图解析使用parseFloat数组的值,然后将它们存储回阵列。那么我想在数组中加起来的数字,并将其存储为另一个变量,dataSum。

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".

我有以下code,但我无法得到它的工作:

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];
}

因此​​,在这一切的目的,我应该能够访问任何已解析的数字的单独数据[0],数据[1],等等,并具有用于dataSum总数。我在做什么错了?

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)

var dataSum = "";

您正在初始化 dataSum 为字符串。对于字符串,在 + = 是一个连接运算符,所以您将获得 100200300400500 由于级联。你应该把它初始化为0:

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 不修改输入参数。浮子返回值。所以,你应该用

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(",");

第二分配将覆盖1号。只要写

The 2nd assignment will override the 1st. Just write

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


(顺便说一句,ECMAScript中5支持这一行:


(BTW, ECMAScript 5 supports this one-liner:

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

这篇关于在JavaScript解析数组数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆