2013-10-05 139 views
-1

我需要一個函數,我可以輸入具有可變數目的子陣列的數組。 函數應該添加每個位置的子陣列的數量。 這是具有三個子陣列的示例輸入陣列(也可以是兩個或多個):在javascript中添加可變數組元素的元素

[ [ [ 12 ], [ 8 ], [ 2 ], [ 9 ], [ 2 ], [ 2 ] ], 
     [ [ 3 ], [ 4 ], [ 2 ], [ 3 ], [ 2 ], [ 2 ] ], 
     [ [ 6 ], [ 2 ], [ 2 ], [ 3 ], [ 2 ], [ 2 ] ] ] 

函數應輸出:

[ 21, 14, 6, 15, 6, 6 ] 
+1

,你到目前爲止做了什麼? – trrrrrrm

+0

'function addarrays(){ var outputarray = []; asyncLoop2(arguments.length-2, function(loop){ outputarray = addtwoarrays(arguments [i],arguments [i + 1]); loop.next(); },function(){return outputarray; }); }」「功能addarrays(){ VAR outputarray = []; asyncLoop2(的arguments.length-2, 函數(循環){ outputarray = addtwoarrays(參數[I],自變量[I + 1]); loop.next(); },function(){return outputarray;}); } [這裏](http://moourl.com/ai24t)是異步循環功能,我打電話給 –

回答

1
var data = [ [ [ 12 ], [ 8 ], [ 2 ], [ 9 ], [ 2 ], [ 2 ] ], 
     [ [ 3 ], [ 4 ], [ 2 ], [ 3 ], [ 2 ], [ 2 ] ], 
     [ [ 6 ], [ 2 ], [ 2 ], [ 3 ], [ 2 ], [ 2 ] ] ]; 

function adder(inputData) { 
    var resultArray = new Array(inputData[0].length); 
    for (var i = 0, len = inputData.length; i < len; i += 1) { 
     for (var j = 0, len1 = inputData[i].length; j < len1; j += 1) { 
      if (resultArray[j]) { 
       resultArray[j] += parseInt(inputData[i][j]); 
      } else { 
       resultArray[j] = parseInt(inputData[i][j]); 
      } 
     } 
    } 
    return resultArray; 
} 

console.log(adder(data)); 

結果

[ 21, 14, 6, 15, 6, 6 ] 
+0

快速回答哇,已經採取了我一個星期左右,thx人 –

+0

@MichaelMoeller不客氣:) – thefourtheye

1
function sumSubArrays(array) { 
    if (array.length == 0) { 
     return new Array(); 
    } 
    var resultLength = array[0].length; 
    var result = new Array(resultLength); 
    for (var i = 0; i < resultLength; i++) { 
     var tmp = 0; 
     for (var j = 0; j < array.length; j++) { 
      tmp += array[j][i][0]; 
     } 
     result[i] = tmp; 
    } 
    return result; 
} 
+0

工作很棒,thx –