我在javascript中有多个数组,我想要对这些数组和最终数组进行求和。
EX: Array1 = [1,9,10,11], Array2 = [5,8,7,2], Total = [6,17,17,13].
答案 0 :(得分:6)
var Array1 = [1,9,10,11];
var Array2 = [5,8,7,2];
var Total = [];
for( var i = 0; i < Array1.length; i++)
{
Total.push(Array1[i]+Array2[i]);
}
顺便说一下,用大写字母开始变量名称感觉很尴尬。
答案 1 :(得分:1)
var Array1 = [1,9,10,11];
var Array2 = [5,8,7,2];
var Total = new Array();
for(var i= 0;i<Math.min(Array1.length,Array2.length);i++){
Total.push(Array1[i]+Array2[i]);
}
alert(Total);
答案 2 :(得分:1)
function aSum(/*arrays list*/){
var total=[],undefined;
for(var i=0,l0=arguments.length;i<l0;i++)
for(var j=0,arg=arguments[i],l1=arg.length;j<l1;j++)
total[j]=(total[j]==undefined?0:total[j])+arg[j];
return total;
}
var Array1 = [1,9,10,11], Array2 = [5,8,7,2], Array3 = [1,2,3,4,8];
console.log(aSum(Array1, Array2, Array3)); // [7, 19, 20, 17, 8]
答案 3 :(得分:0)
ES6中的箭头功能
var Array1 = [1,9,10,11];
var Array2 = [5,8,7,2];
var sum = Array1.map((val, idx) => val + Array2[idx]);
console.log(sum);
&#13;