-1

I'm doing a scoring app as practice, and I'm trying to get an object to calculate the total score for a player. Here is the part I'm struggling with:

totalScore: function () {
  "use strict";
  debugger;
  var sum = 0;
  for (var i = 0; i < this.players[i].length; i++) {
    for (var n = 0; n < this.players[i].score[n].length; n++) {
      sum += this.players[i].score[n];
    }
    this.players[i].totalScore = sum;
  }  }

So I have a main object scoreTable. players is an array of objects which includes another array called score. So what I'm trying to do is create a totalScore object function that runs a loop through the players array that loops on each score array and finds the sum of that array.

I don't know why, but when I run through it on the dubugger, it goes into the first for loop, finds the first array of players, then just skips to the end of the function without running the next loop. I'm not sure why it's doing that.

1
  • I bet sum must be inside the loop. Commented Oct 9, 2017 at 18:31

2 Answers 2

3
for (var i = 0; i < this.players[i].length; i++) {
    for (var n = 0; n < this.players[i].score[n].length; n++) 
}

This should be:

for (var i = 0; i < this.players.length; i++) {
    for (var n = 0; n < this.players[i].score.length; n++) 
}
Sign up to request clarification or add additional context in comments.

1 Comment

and the next for loop too score.length
0

Try following:

totalScore: function () {
    for (var i = 0; i < this.players.length; i++) {
        var player = this.players[i];
        player.totalScore = 0;
        for (var n = 0; n < player.score.length; n++) {
          player.totalScore += player.score[n];
        }
    }
}

This fixes not only syntax errors, but also the sum-logic itself: sum variable from initial post won't reset for each new player in the top-level loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.