我正在尝试创建一个使用localStorage的图书追踪器应用。但是,当我设置一个项目时-发生的是没有给出错误消息,但没有记录到localStorage。这是我的代码:
//var currentId = parseInt(localStorage.getItem("currid"))+1;
var nameOfItem = "bookPackage"+id;
localStorage.setItem(nameOfItem, readBooks);
假设currid
已在localStorage中预先设置为数字。
当我进入控制台并输入localStorage
时,结果如下:
Storage {length: 0}
为什么不起作用?
编辑:readBooks
是一个对象。
答案 0 :(得分:1)
您只能将字符串存储到本地存储中,如果要存储对象,则需要先使用JSON.stringify(obj)。
var str = "22";
localStorage.setItem('key', str);
var getStr = localStorage.getItem('key');
console.log(parseInt(getStr));
let obj = {a: 'a1', b: 'a2'};
localStorage.setItem('key2', JSON.stringify(obj));
let getObject = localStorage.getItem('key2');
console.log(JSON.parse(getObject));
答案 1 :(得分:1)
就像@sonEtLumiere已经提到的那样,您只能将字符串存储到本地/会话存储中,因此,如果您有对象/数组,则在将它们存储到本地/会话存储中之前必须先用JSON对其进行字符串化。我不确定“ readBooks”是什么,但是由于它是复数形式,所以我假设它是一个数组。因此,您需要使用JSON.stringify(data)来存储该信息。
当您需要从本地/会话存储中检索对象/数组数据时,必须使用JSON解析数据。
JSON.parse(数据)
请记住,将IN字符串化到存储中,解析出存储。