-2

I want a for loop that sums all the results of the 8 values of the array

total=respuestas[1]+respuestas[2]+respuestas[3]+respuestas[4]+respuestas[5]+respuestas[6]+respuestas[7]+respuestas[8];
Sarath Chandra
  • 1,850
  • 19
  • 40
JorgeAlberto
  • 61
  • 1
  • 13

2 Answers2

1

All you need is an iterated summation over the indices of the array.

var total =0;   
var i=0;
for( i=1; i<=8;i++){ 
    total += respuestas[i]; 
}

Another way to write the same thing, using the forEach loop.

var total = 0 ;
respuestas.forEach(function(entry){
    total += entry ;
});
Sarath Chandra
  • 1,850
  • 19
  • 40
0

you can try this:

var sum = 0;
for (i in respuestas) {
  sum += respuestas[i];
}

sum contains your result. The for..in loop will count through all your objects properties (works for arrays as well as you can see). I think it looks cleaner than a normal for loop.

rototof
  • 1
  • 1
  • 2
    As a thumb rule, do not use the for loop with the in for an array. The for-in is intended for enumerable properties of an object, and bite the elements of an array. – Sarath Chandra Nov 26 '15 at 20:50