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

217
Visualizações
Javascript localStorage not working it overwrites object

I have 20 buttons and 20 links and descriptions inside info_array. I add click event listener to each button. On click function inside addEventListener must save unique info inside localStorage with incrementing object keys on each new button click.

Problem is that function works and saves Objects with unique value inside localStorage like 0,1,2,3,... till 10th object. When object keys reach 10 then 11th object with key 11 is not saving in localStorage, code just overwrites 10th object every time i clicked 11th,12th,13th,... button just overwrites value of 10th object rather creating and saving new object with new object key like 11,12,13,14,...

I can't understand what is wrong with my code because it works till 10th object.

Code:

for (let i = 0; i < 19; ++i) {

    let btn = document.createElement('BUTTON');

    btn.addEventListener('click',function(e){
        e.stopPropagation();

        let newsList = localStorage,
        keys         = Object.keys(localStorage).sort(),
        match        = false,
        news         = {
            "title":info_array[i].title,
            "description":info_array[i].description
        };

        if (nl.length > 0) {

            // check if element exists in localStorage
            for(let n = 0; n < newsList.length; ++n){
                if (JSON.parse(newsList[keys[n]]).link == info_array[i].link) {
                    match = true;
                }
            }

            // if object is unique save in localStorage
            if (!match) {
                let key = (parseInt(keys.pop())+1).toString();
                localStorage.setItem(key,JSON.stringify(news));
            }
            
        }else{
            // if localStorage is empty add first object
            localStorage.setItem(0,JSON.stringify(news));
        }

    },{passive:true});

    html.appendChild(element);
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's because of this line:

keys = Object.keys(localStorage).sort()

Specifically, the bug is caused by .sort()

Strings are sorted in dictionary order. So your keys are:

0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9

This logic is similar to how the words

app, big, branch, cut, dig, eye, fig, gem

are sorted. The word branch comes afer big and not gem because it starts with b. Similarly 10 comes after 1 and not 9 because it starts with the letter 1.

When you pop the last key and add 1 to it you will get 10 because the last key is always 9.

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