简体   繁体   English

如何在js中对数组元素求和?

[英]How to sum array elements in js?

im having a problem on my elements.我的元素有问题。 how can i sum array elements like this?.我怎样才能对这样的数组元素求和?

<input type="text" name="noheadRecieved[0][0]">
<input type="text" name="noheadRecieved[0][1]">
<input type="text" name="noheadRecieved[0][2]">

<input type="text" name="noheadRecieved[1][3]">
<input type="text" name="noheadRecieved[1][4]">
<input type="text" name="noheadRecieved[1][5]">

and so on...等等...

i want to sum all elements with first key is 0 and separate sum of elements with first key is 1.我想对第一个键为 0 的所有元素求和,第一个键为 1 的单独元素总和。

Try this : you can use map to store sum for 0,1, etc keys and retrieve it again as per your use.试试这个:您可以使用 map 来存储 0,1 等键的总和,并根据您的使用情况再次检索它。

 $(function(){ var sumMap = {}; $('input[name^="noheadRecieved"]').each(function(){ var name = $(this).attr('name'); var values = name.match(/\\d/g); var existingVal = parseInt(sumMap[values[0]]) | 0; var newVal = existingVal + parseInt($(this).val()); sumMap[values[0]] = newVal; }); alert(sumMap[0]); alert(sumMap[1]); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <input type="text" name="noheadRecieved[0][0]" value="1"> <input type="text" name="noheadRecieved[0][1]" value="2"> <input type="text" name="noheadRecieved[0][2]" value="3"> <input type="text" name="noheadRecieved[1][3]" value="3"> <input type="text" name="noheadRecieved[1][4]" value="1"> <input type="text" name="noheadRecieved[1][5]" value="3">

 var results = Array.prototype.slice.call(document.querySelectorAll('input[name^=noheadRecieved]')).reduce(function(p, e) { var i = parseInt(e.name.split(/\\D+/)[1]); return p[i] = (p[i] || 0) + parseFloat(e.value), p; }, []); console.log(results);

var sums = [];

for(var i = 0; i < noheadRecieved.length; i++)
{
    sum[i] = 0;
    for(var j = 0; j < noheadRecieved[i].length; j++)
        sums[i] += noheadRecieved[i][j];
}

You can then access the sum of all elements where the first key is 0 by using sum[0].然后,您可以使用 sum[0] 访问第一个键为 0 的所有元素的总和。

I think below sample code may solve your issue.我认为下面的示例代码可以解决您的问题。

var results = []; 
var addValue = function (index, value){
    var val = results[index];
    if(val && val != ""){
        results[index] += value;
    }else{
        results[index] = value;
    }
};

$("input[name^='noheadRecieved']").each(function(index, object){
    var index = parseInt($(object).attr("name").split(/\D+/)[1]);
    addValue(index, parseInt($(object).val()));
});

alert(" Key 0's sum = "+results[0]+" Key 1's sum = "+results[1]);

Sample Code示例代码

Please let me know if you will face any issue.如果您会遇到任何问题,请告诉我。

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

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