我正在尝试向当前的 localStorage 对象添加一个新对象,但没有成功。最后,我没有在 localStorage 中拥有两组数据,而是得到了最后一组。对我做错了什么有任何见解吗?谢谢
这是我正在尝试做的事情:
// add the first student
var newStudent = [{
"name": "John",
"age": 21,
"nationality": "Spanish"
}];
localStorage.setItem("students", JSON.stringify(newStudent));
// Retrieve the object from storage to add a new student
var retrievedObject = localStorage.getItem("students");
var stored = JSON.parse(retrievedObject);
// add a new student
var newStudent2 = [{
"name": "Mary",
"age": 20,
"nationality": "German"
}];
var stored = Object.assign(stored, newStudent2);
// Update the storage
localStorage.setItem("students", JSON.stringify(stored));
var result = localStorage.getItem("students");
console.log(result);
最佳答案
你应该存储数组,而不是对象;
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);
关于javascript - 将数据附加到 localStorage 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35963412/