[英]Local Storage in chrome
i need help!我需要帮助!
I am looking to uses chrome local storage in one of my apps.我希望在我的一个应用程序中使用 chrome 本地存储。 Basically this is supposed to be a shopping list app that store locally previously entered items as an object in JavaScript.基本上,这应该是一个购物清单应用程序,它将本地先前输入的项目存储为 JavaScript 中的 object。
i must be doing something wrong because when there is nothing in local storage and i add an item i gets saved fine but then whenever i add a second item, the previous item gets replaced.我一定是做错了什么,因为当本地存储中没有任何内容并且我添加了一个项目时,我会很好地保存,但是每当我添加第二个项目时,前一个项目就会被替换。
Here's my code so far到目前为止,这是我的代码
function useLocalStorage(shoppingListItem){
let shoppingApp = {};
if (localStorage.getItem(shoppingApp) === null){
shoppingApp.shoppingList = [];
}
else {
shoppingApp.shoppingList = JSON.parse(localStorage.getItem('shoppingApp.shoppingList'));
}
shoppingApp.shoppingList.push({
shoppingListItem : shoppingListItem,
checked : false,
});
localStorage.setItem(shoppingApp.shoppingList.shoppingListItem,
JSON.stringify(shoppingApp.shoppingList));
}
Did you see how your localStorage looks like after executing the function?执行 function 后,您看到 localStorage 的样子了吗?
If you did not do typos in code:如果您没有在代码中输入拼写错误:
localStorage.setItem(
shoppingApp.shoppingList.shoppingListItem,
JSON.stringify(shoppingApp.shoppingList)
);
The first argument will return undefined
, you are trying to access proprty of shoppingListItem
on shoppingList
which is array.第一个参数将返回undefined
,您正在尝试访问数组shoppingListItem
上的shoppingList
属性。 To get any value you need to access the item directly with for example shoppingApp.shoppingList[0]
.要获得任何价值,您需要直接访问该项目,例如shoppingApp.shoppingList[0]
。 Because of this error(?) for me it saves the list in undefined
key.由于这个错误(?)对我来说,它将列表保存在undefined
的键中。
let shoppingApp = {};
if (localStorage.getItem(shoppingApp) === null){
shoppingApp.shoppingList = [];
}
This if statement is always true
.此 if 语句始终为true
。 What you are doing is trying to access item with key {}
and because there is no key like that in your localStorage it returns null
so your new shopping list is empty.您正在做的是尝试使用键{}
访问项目,因为在您的 localStorage 中没有类似的键,它返回null
所以您的新购物清单为空。 You probably wanted to use here string: if (localStorage.getItem('shoppingApp') === null)
.您可能想在这里使用字符串: if (localStorage.getItem('shoppingApp') === null)
。 If you were to write the {}
as a key so you could access it later - it would get parsed and the key would be "[object Object]" so I do not think that is your intended behaviour.如果您要将{}
写为键,以便以后可以访问它 - 它会被解析并且键将是“[object Object]”,所以我认为这不是您的预期行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.