Why isn't localStorage accepting my object?
本问题已经有最佳答案,请猛点这里访问。
我需要在
1 | var data = {lastEdit:"September", expires:"December", records:[{arrives:"12:45", departs:"12:51"}, {arrives:"13:03", departs:"13:04"}]}; |
我试过了,但它说‘未定义’:
1 2 | localStorage.setItem("dataStore1", data); var output = localStorage.getItem("dataStore1"); |
我能做些什么来修复它?
解决了的使用
通过使用Web存储API:
"Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do)."
不能在本地存储中存储复杂的
相反,您应该将对象序列化为一个字符串[提示:
1 2 3 4 5 6 7 8 9 | var testObject = { 'one': 1, 'two': 2, 'three': 3 }; // Put the object into storage localStorage.setItem('testObject', JSON.stringify(testObject)); // Retrieve the object from storage var retrievedObject = localStorage.getItem('testObject'); console.log('retrievedObject: ', JSON.parse(retrievedObject)); |