Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
Saving scores to local storage

I'm implementing a dice game, which will store the results of the 2 players. I'm having an issue saving the scores, when I console.log I get the new scores only. What is the issue here?

window.onload = (event) => {
  throw_dice();
};
var scores = { player1: 0, player2: 0 };

function throw_dice() {
  let x = Math.floor(Math.random() * 6) + 1;
  let img1 = document.getElementById("img1");
  let y = Math.floor(Math.random() * 6) + 1;
  let img2 = document.getElementById("img2");
  img1.src = "./images/dice" + x + ".png";
  img2.src = "./images/dice" + y + ".png";

  if (x > y) {
    document.getElementById("title").innerHTML = "PLAYER 1 WINS";
    scores.player1 = scores.player1 + 1;
  } else if (x == y) {
    document.getElementById("title").innerHTML = "DRAW";
  } else {
    document.getElementById("title").innerHTML = "PLAYER 2 WINS";
    scores.player2 = scores.player2 + 1;
  }

  saveScores();
  getScores();
}

function saveScores() {
  localStorage.setItem("score", JSON.stringify(scores));
}
function getScores() {
    var x = localStorage.getItem('score');

    console.log('x', JSON.parse(x));
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

On pageload, you're doing

var scores = { player1: 0, player2: 0 };

and then updating that object inside throw_dice and saving to storage. On that line, you need to retrieve the object from local storage on pageload instead, otherwise you'll be never reading (and thereby overwriting) the existing scores in storage in saveScores.

var scores = JSON.parse(
  localStorage.getItem('score') || '{ "player1": 0, "player2": 0 }')
);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda