最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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>

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>
Share Improve this question edited Jul 12, 2017 at 19:07 CChristiansen asked Jul 12, 2017 at 3:42 CChristiansenCChristiansen 471 gold badge1 silver badge6 bronze badges 4
  • 2 You will want to learn about objects and properties, to use them as a structure instead of those many variables. Also, array and object literals. – Bergi Commented Jul 12, 2017 at 3:45
  • 1 ...and learn about function parameters. – nnnnnn Commented Jul 12, 2017 at 3:46
  • Your loop is fine. All your code is missing is the declaration of votes as a parameter of the function, and the actual call (e.g. totalVotes(votes3)). – Bergi Commented Jul 12, 2017 at 3:47
  • Be careful about asking StackOverflow for your homework questions. If you post something directly from here you will almost certainly be "asked" about it by a teacher. Your code in the HTML is almost correct for calculating totals, you should say var i = 0 or let i = 0 instead of i=0. – zetavolt Commented Jul 12, 2017 at 4:03
Add a comment  | 

5 Answers 5

Reset to default 10

You can use reduce Method of array. Reduce Method gives concatenated value based on elements across the Array. For Example :

const sum = [1,2,3].reduce(function(result,item) {
 return result + item;
}, 0);
console.log(sum);

The above code gives the output 6 that is the sum of given array. You can check other methods of array on my Gist: Iterate_Over_Array.js

You just need to pass in the array you want to iterate over:

var vote1 = [45125, 44498, 5143]

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

// better alternative
function tallyVotes(votes) {
  return votes.reduce((total, vote) => total + vote, 0);
}

console.log('for loop: ', totalVotes(vote1));
console.log('reduce: ', tallyVotes(vote1));

I would suggest to create Javascript Object instead of array of different properties.If you use Object then you will have to create Array of Objects with following structure -

var first_object = {
     'name':"Jeffrey Hart",
     'party':"D",
     'race':"1st Congressional District",
     'vote':"45125"
}

You will create object for each record and use Arrays.push to add into your array. Lets assume array is records, then use

records.push(first_object)

After Adding all the records then you will have arrays of Objects now you can tracer through it with simple forEach loop

var total = 0;
records.forEach( function (record)
{
    total+= record.vote;
});

If you are new to Javascript I would recommend to read

JavaScript: The Good Parts By Douglas Crockford

http://shop.oreilly.com/product/9780596517748.do

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;.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论