通过本地存储保存数据时存在问题



在数据保存到本地存储的过程中。我想在一个名为'DB'的键中存储对象。但是我得到一个错误,说"list。Push不是一个函数。有什么问题吗?

let list = JSON.parse(localStorage.getItem('DB'));
const index = number++;
if (!list) {
const arr = [];
arr.push({
todo: text,
index: index
});
localStorage.setItem("DB", JSON.stringify(arr));
} else {
list.push({
todo: text,
index: index
});
console.log(list);
localStorage.setItem("DB", JSON.stringify(list));
}

如果已经在存储项DB中存储了不能解析为数组的内容,则代码将失败。如果我运行两次它会做我认为你想要它做的事情,我在localStorage中得到一个带有两个对象的字符串化数组。我建议您再试一次,如果您有问题,请检查您的localStorage中的内容。

顺便说一句,您的代码可以简化一点。例如:
let list = JSON.parse(localStorage.getItem('DB'));
// Maybe print out list here, to see what it is immediately after parsing 
console.log('list:', list);
const index = number++;
if (!list) {
list = [];
});
list.push({
todo: text,
index: index
});
localStorage.setItem("DB", JSON.stringify(list));

最新更新