Append data to localStorage object

后端 未结 4 635
夕颜
夕颜 2021-02-10 11:08

I\'m trying, unsuccessfully, to add a new object to a current localStorage object. Instead of, at the end, having two sets of data in localStorage, I get the last one. Any insig

4条回答
  •  既然无缘
    2021-02-10 11:33

    You should store array, not an object;

    var students = [];
    
    var student1 = { s: 1 };
    
    students.push(student1);
    
    localStorage.setItem("students", JSON.stringify(students));
    
    var stored = JSON.parse(localStorage.getItem("students"));
    
    var student2 = { s: 2 };
    
    stored.push(student2);
    
    localStorage.setItem("students", JSON.stringify(stored));
    
    var result = JSON.parse(localStorage.getItem("students"));
    
    console.log(result);
    

提交回复
热议问题