简体   繁体   English

添加特定的数组值

[英]Adding Specific Array Values

Ok, so I have an array. 好的,所以我有一个数组。

var array = ['159','350','317','350','138','163','317','367','352','317'];

I want to loop through the array and take only specific values each time the loop runs and put these into another array. 我想遍历数组,每次循环运行时仅获取特定值,然后将其放入另一个数组中。 Eg taking every 3rd item in the array, so.... 例如,取数组中的每个第三项,所以...

var a = 3;
var colArray = [];

for (var i = 0; i < a; i++) {
  colArray[i] = [];
  for (var k = i; k < array.length; k += a) {
     colArray[i].push(array[k]);
  };    
}; 

console.log(colArray);

....would give this in the console on the first iteration..... ....将在第一次迭代时在控制台中给出.....

159, 350, 317, 317

All that works fine, but want I then want to do is add up the values in each array of colArray . 一切正常,但是我想做的就是将colArray每个数组中的值colArray I DON'T want the total of each array, but want the 1st value to be added to 0, the 2nd to 0 + 1st and so on, to give something like this.... 我不希望每个数组的总数,但希望将第一个值添加到0,将第二个值添加到0 + 1st,以此类推,以给出类似的结果。

159, 509, 826, 1143 

jsFiddle jsFiddle

I think this is what you want, there is probably a better way to do it, but this worked for me. 我认为这是您想要的,也许有更好的方法可以这样做,但这对我有用。

  var array = ['159','350','317','350','138','163','317','367','352','317','159','138'];

var a = 3;
    var colArray = [];
    for (var i = 0; i < a; i++) {
      colArray[i] = [];

      for (var k = i; k < array.length; k += a) {
        if(k<a){
         colArray[i].push(Number(array[k]));
        }else{
         colArray[i].push(Number(array[k]) + Number(colArray[i][(k-a-i)/a]));
        }
      };    
    }; 

    console.log(colArray);

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

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