Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda