我一直在编写一些代码,将一个项目添加到本地存储阵列,但遇到了一个没有更新阵列的问题。由于localStorage不允许数组,我一直在转换为字符串。
function addItem(add_item) {
if (localStorage.getItem("list_items") === null) {
localStorage.setItem("list_items", "");
}
else {
"Something has gone horribly wrong!"
}
// Check if item is already added
if(existingEntries == null) existingEntries = [];
else {
existingEntries = JSON.parse(localStorage.getItem("list_items"));
}
// Set entry to the currently selected item
var entry = add_item;
// Check if item is in string
var exists = existingEntries.includes(entry);
// Add item if it's not already in the array
if (exists == false) {
existingEntries.push(entry);
localStorage.setItem("list_items", JSON.stringify(existingEntries));
}
}
由于某种原因,本地存储未使用添加的新值进行更新。任何想法为什么?提前谢谢。
答案 0 :(得分:2)
你已经过度复杂了。
简化为:
function addItem(add_item) {
// parse existing storage key or string representation of empty array
var existingEntries = JSON.parse(localStorage.getItem("list_items") || '[]');
// Add item if it's not already in the array, then store array again
if (!existingEntries.includes(add_item)) {
existingEntries.push(add_item);
localStorage.setItem("list_items", JSON.stringify(existingEntries));
}else{
// or tell user it's already there
console.log(add_item + ' already exists')
}
}
答案 1 :(得分:0)
如果您的本地存储区中的数据包含密钥'list_items'
,则localStorage.setItem("list_items", "my new data");
将覆盖旧数据。