开发者

Building an array out of values from another array

This is a follow up from a question of mine that was just answered concerning parsing numbers in an array.

I have an array, data[], with numbers that I'd like to use in a calculation an开发者_JAVA百科d then put the resulting values into another array.

So say data[0] = 100. I'd like to find a percentage using the calculatin, (data[0]/dataSum*100).toFixed(2) where dataSum is the sum of all the numbers in data[].

I've tried:

dataPercentage = [];

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

    // looping through data[i] and setting it equal to dataPercentage.
    dataPercentage[] = (data[i]/dataSum*100).toFixed(2);

    // thought maybe I was overriding dataPercentage everytime I looped? 
    dataPercentage[] += (data[i]/dataSum*100).toFixed(2); 
}

I also tried just setting dataPercentage = [(data/dataSum*100).toFixed(2)], but I think this creates a nested array, which I don't think is what I need.


You have to calculate the sum of all values in data before you calculate the percentage. In your code you always use the sum up to the ith item of the data array.

var dataSum = 0.0;
var dataPercentage = [];

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

for (var i=0; i < data.length; i++) {
    dataPercentage[i] = (data[i]/dataSum*100).toFixed(2); 
}

I don't know what you try to achieve with your second dataPercentage[] line.


dataPercentage.push((data[i]/dataSum*100).toFixed(2))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜