在HTML5 localStorage中存储对象的示例代码
2021-06-06 04:10
1276 查看
我想在HTML5中存储一个JavaScript对象localStorage
,但是我的对象显然正在转换为字符串。
我可以使用来存储和检索原始JavaScript类型和数组localStorage
,但是对象似乎无法正常工作。应该吗
这是我的代码:
var testObject = { 'one': 1, 'two': 2, 'three': 3 }; console.log('typeof testObject: ' + typeof testObject); console.log('testObject properties:'); for (var prop in testObject) { console.log(' ' + prop + ': ' + testObject[prop]); } // Put the object into storage localStorage.setItem('testObject', testObject); // Retrieve the object from storage var retrievedObject = localStorage.getItem('testObject'); console.log('typeof retrievedObject: ' + typeof retrievedObject); console.log('Value of retrievedObject: ' + retrievedObject);
控制台输出为
typeof testObject: object
testObject properties:
one: 1
two: 2
three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]
在我看来,该setItem
方法是在存储输入之前将输入转换为字符串。
解决方案:
再次查看Apple,Mozilla和Mozilla文档,该功能似乎仅限于处理字符串键/值对。
一种解决方法是在存储对象之前先对它进行字符串化处理,然后在检索它时对其进行解析:
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));
到此这篇关于在HTML5 localStorage中存储对象的文章就介绍到这了,更多相关HTML5 localStorage存储对象内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!
相关文章推荐
- 将对象存储在HTML5 localStorage中
- HTML5数据存储---使用clear()方法清除localStorage保存对象的全部数据
- HTML5数据存储---使用clear()方法清除localStorage保存对象的全部数据
- 阿里云对象存储OSS配置介绍设置,上传代码示例
- Js 操作浏览器本地存储对象:HTML5 localstorage
- html5本地存储localStorage 存储json对象存储格式问题
- html5本地存储localStorage 存储json对象存储格式问题
- HTML5 LocalStorage本地存储和sessionStorage使用
- HTML5 LocalStorage 本地存储
- HTML5本地存储Localstorage
- 将通过<input type="file">上传的txt文件存储在localStorage,提取并构建File对象
- 获得Javascript对象属性个数的示例代码
- html5实现多文件的上传示例代码
- HTML5 LocalStorage 本地存储
- .NET core高性能对象转换示例代码
- Hadoop RCFile存储格式详解(源码分析、代码示例)
- html5弹跳球示例代码
- JS+HTML5 FileReader对象用法示例
- Html5生成验证码的示例代码
- Python中的数据对象持久化存储模块pickle的使用示例