简体   繁体   English

通过使用另一个数组的对象的值来增加数组对象的值

[英]Increment value of array object by using values of another array's objects

I'm trying to figure out how to get cumulative values from a data table that a user enters values in. I've stored all of the data into an array representing the raw data , and I am trying to increment an array which is a copy of the array representing the raw data in order to obtain the cumulative data for the graph. 我试图弄清楚如何从用户输入值的数据表中获取累积值。我已经将所有数据存储到表示原始数据的数组中,并且试图增加一个数组,该数组是代表原始数据的数组副本,以获得图形的累积数据。 I am trying to do this by incrementing each value object of the array to the values of each index of the raw data array up to the current index. 我正在尝试通过将数组的每个值对象增加到原始数据数组的每个索引的值直至当前索引来实现此目的。 I'm doing this through a loop, but it doesn't seem to be working. 我正在通过循环执行此操作,但是它似乎没有用。 My code for the function is here: 我的函数代码在这里:

function generateChartData() {
    var rawData = [];
    var chartData = [];
    jQuery('.data-row').each(function () {
        var date = jQuery(this).find('.data-category').val();
        var value = jQuery(this).find('.data-value').val();
        var value2 = jQuery(this).find('.data-value2').val();
        if (date != '') {
            rawData.push({
                date: date,
                value: value,
                value2: value2

            });
        }
    });
    for (var i = 0; i < rawData.length; i++)
    {
        chartData[date][i] = rawData[date][i];
        for(var j = i; j >= 0; j--)
        {
            chartData[i][value]+=rawData[j][value];
            chartData[i][value]+=rawData[j][value2];
        }
    }

    return chartData;
}

Here is the jsfiddle 这是jsfiddle

You're not properly accessing array and object elements. 您没有正确访问数组和对象元素。 And you can just use a simple variable to hold the running total. 您可以只使用一个简单的变量来保存运行总计。

var valueSum = 0;
var value2Sum = 0;
for (var i = 0; i < rawData.length; i++) {
    rd = rawData[i];
    valueSum += rd.value;
    value2Sum += rd.value2;
    chartData.push({
        date: rd.date,
        value: valueSum,
        value2: value2Sum
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM