JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Using For Loops with Arrays

Vic Mercier
Vic Mercier
3,273 Points

average calculator

Is someone able to do an average calculator with for loop an array?If yes show me how.

4 Answers

Vic Mercier
Vic Mercier
3,273 Points

var numbers = [1,2,3]; var total; for(var i = 0; i < numbers.length;i += 1){ total += numbers[i]; } var average = total/numbers.length; alert(average); Is it good.If not show me your solution.

Steven Parker
Steven Parker
81,790 Points

That's good except you forgot to initialize your total.

So instead of: "var total;", you might write: "var total = 0;"

Steven Parker
Steven Parker
81,790 Points

Give this a try yourself.

If you combine what you just learned about loops and arrays with what you did in JavaScript Basics, you should be able to at least give it a try.

Vic Mercier
Vic Mercier
3,273 Points

Yes I know but I finished the array loop and object and i am not able

Steven Parker
Steven Parker
81,790 Points

You might use a technique from the courses: start with breaking the project down into separate tasks, define the tasks with comments, and then fill in code for each. Here's a sample:

// construct an array with the proper contents

// create a variable to hold a total

// make a loop that will run once for each item in the array

    // inside the loop, add each item to the total

// after the loop, divide the total by the number of items and store that in a new variable

// finally, pick a way to display the average.  alert?  log?  write into the document?
Vic Mercier
Vic Mercier
3,273 Points

var numbers = [1,2,3]; var total; for(var i = 0; i < numbers.lenght; i +=1){ total += numbers[i];

} Am I well started? And I will divide the total by numbers.lenght

Steven Parker
Steven Parker
81,790 Points

You wrote "lenght" instead of "length", but otherwise it looks like you got the first 4 items there. Just two more and you'll have it functioning.

Vic Mercier
Vic Mercier
3,273 Points

Should I use a for loop?