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

159
Visualizações
Problem with Javascript localStorage for-loop

I am using localStorage to store incoming message: {"lastTid":22,"Hour":10,"min":31,"Second":34} where the time is increasing in every new incoming object, e.g. next object: {"lastTid":22,"Hour":10,"min":31,"Second":35}.

The new messages are being stored in localStorage correctly as seen here:

enter image description here enter image description here

My Javascript code implements the localStorage.getItem and .setItem correctly to retrieve and get my incoming data message, which will be rendered with .innerHTML to var hst, which hst = document.getElementById("highscores"). all code below

The ElementId "highscores" is assigned to <table> tag in my html and comes out as seen here: enter image description here

#js code snippet#

     var hst = document.getElementById("highscores");

     function onMessageArrived(message) {
        
        var data = JSON.parse(message.payloadString);
        var highScores = [data];

        var array = JSON.parse(localStorage.getItem('highscores') || '[]');
        array.push(highScores);

        localStorage.setItem('highscores', JSON.stringify(array));
        for (var i = 0; i < array.length; i++) {
        hst.innerHTML += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
        }
    };

My problem is, because of my For loop, when a new message arrives, my loop goes through and renders the previous message and the new message, while the old message is still in the table(please see the table image above). It is displaying object 0, object 0 & 1, then object 0, 1 & 2 all in the same table. Instead of 0, then 1 after, then 2 ... n.

I wish to display the values in proper order and also keep those values even after the page is reloaded. Desired result:

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Don't append directly hst.innerHTML +=...

try something like this

let html = ''
for (var i = 0; i < array.length; i++) {
        html += "<tr><td>" + array[i][0].Hour + ":"+ array[i][0].min + ":" + array[i][0].Second + "</td><td>" + array[i][0].lastTid + "</td></tr>";
}
hst.innerHTML = html

about 4 years ago · Juan Pablo Isaza Relatório

0

I think the problem is your always appending the array content at hst.innerHTML each incoming message, so the previous loop content remains. It's also not recommended for performance to manipulate DOM inside loops.

let res = '';
for (var i = 0, l = array.length; i < l; i++) {
  res += '<tr><td>' + array[i][0].Hour + ':' + array[i][0].min + ':' + array[i][0].Second + '</td><td>' + array[i][0].lastTid + '</td></tr>';
}
hst.innerHTML = res; // You overwrite the content instead of appending each time.
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