JavaScript, Using a for loop to calculate the sum of all the values within an array

Viewed 25465

I just starting using JavaScript a couple weeks ago and still struggling a bit. I need to create a loop that calculates the sum of all values coming from a votes array in a separate .js file.

The function has a single parameter, votes, representing one of the five vote arrays (vote1 through vote5). Add the following commands to the function:

a. Declare a variable named total, setting its initial value to 0.

b. Create a for loop that loops through each of the items in the votes array, adding that item’s value to the total variable.

c. After the for loop is completed, return the value of the total variable from the function.

Heres my html file.

<script>
    function totalVotes()
    {
        var total = 0;

        for (i=0; i < votes.length; ++i)
            {
                total += votes[i];
            }
            return total;
    }

</script>
5 Answers

You can add the numbers like below

let total = 0;
for (let i = 0; i < this.state.seatArray.length; i++) {
    total += total + parseInt(this.state.seatArray[i].price);
}

Thank you

You can add the numbers like below

for(let i = 0; i < product.length; i++)
 {
   var count1=+product[i].Pending;
   var count2=+product[i].Competed;
   this.totalCount=this.totalCount+(+count1)+(+count2);
}

Declare totalCount globally on top totalCount:number=0;.

Related