Winston Brown
Winston Brown

Reputation: 15

How do I add numbers one after the other

I tried to add the numbers one after the other.

For example, if the number was 10 and then 4 the output would be 14.

let getPlayer2Value = document.querySelector(".getValueP2")
getPlayer2Value.addEventListener("click", init);

function init() {    
  window.roundScore = 0;
  window.diceValue =  Math.floor(Math.random() * 6) + 1;
  window.player2Score = document.querySelector(".totalScoreP2");

  getPlayer2Value.addEventListener("click", () =>
  {
    roundScore += dice;
    player2Score.innerHTML = roundScore;
  });
}

Upvotes: 0

Views: 66

Answers (2)

Luís Ramalho
Luís Ramalho

Reputation: 10198

In order to do that you'll have to separate the init() that sets roundScore = 0 from the event that triggers the adding of numbers one after another. Otherwise, you're constantly setting it to zero. See the snippet below for example:

let initializer = document.querySelector(".init");
let player2Score = document.querySelector(".totalScoreP2");
let getPlayer2Value = document.querySelector(".getValueP2");

let roundScore;

function init() {
  roundScore = 0;
  player2Score.innerHTML = roundScore;
  explanation.innerHTML = `init clicked, roundScore = 0`;
}

getPlayer2Value.addEventListener("click", () => {
  let diceValue = Math.floor(Math.random() * 6) + 1;
  explanation.innerHTML = `${roundScore} (previous roundScore) + ${diceValue} (diceValue)`;
  roundScore += diceValue;
  player2Score.innerHTML = roundScore;
});

initializer.addEventListener("click", init);
<button class="init">Init</button>
<button class="getValueP2">getValueP2</button>
<div class="totalScoreP2"></div>
<small id="explanation"></small>

Upvotes: 3

Kerim G&#252;ney
Kerim G&#252;ney

Reputation: 1258

You can do

firstNumber += secondNumber

or

firstNumber = firstNumber + secondNumber

You're already useing += but I think you have a typo. It should be diceValue not dice.

Upvotes: 1

Related Questions