Need help with Iterate Through an Array with a For Loop [Solved]

Need help with Iterate Through an Array with a For Loop [Solved]



I can’t understand quite well this challenge. It seems that the only thing that I’ve to do is to read an array with a for loop, but when I try to execute, it’s showing me two errors:

        total should be declared and initialized to 0

So I tried to declare and initialize like this: var total=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
total should equal 20
Why 20? The values for myArray are only 5 myArray[2,3,4,5,6]

So I modified my code and try this, but it’s still raising the first error about declaration and initialization.

// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];

// Setup
var myArr = [ 1, 2, 3, 4, 5, 6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var total=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
for(i=0; i < myArr.length; i++){
for (i=0; i < myArr.length; i++){
total = myArr[i];

Any help?


You need to declare and initialize a variable

As in the example

var total = 0;

which updates with each value in the array

total += myArr[i];

in your code

var total=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

you are creating a new array with 20 values all equal to 0


Thanks for you clarification,

I understood that I’ve to create an an array, and add values (insert into) from myArr in total array, not sum them.

Now it’s clear and easier.