最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
在HTML5 localStorage中存储对象的示例代码
时间:2025-07-13 09:00:01 编辑:袖梨 来源:一聚教程网
我想在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 storagelocalStorage.setItem('testObject', testObject);// Retrieve the object from storagevar retrievedObject = localStorage.getItem('testObject');console.log('typeof retrievedObject: ' + typeof retrievedObject);console.log('Value of retrievedObject: ' + retrievedObject);控制台输出为
typeof testObject: objecttestObject properties: one: 1 two: 2 three: 3typeof retrievedObject: stringValue of retrievedObject: [object Object]
在我看来,该setItem方法是在存储输入之前将输入转换为字符串。
解决方案:
再次查看Apple,Mozilla和Mozilla文档,该功能似乎仅限于处理字符串键/值对。
一种解决方法是在存储对象之前先对它进行字符串化处理,然后在检索它时对其进行解析:
var testObject = { 'one': 1, 'two': 2, 'three': 3 };// Put the object into storagelocalStorage.setItem('testObject', JSON.stringify(testObject));// Retrieve the object from storagevar retrievedObject = localStorage.getItem('testObject');console.log('retrievedObject: ', JSON.parse(retrievedObject));到此这篇关于在HTML5 localStorage中存储对象的文章就介绍到这了,更多相关HTML5 localStorage存储对象内容请搜索一聚教程网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持一聚教程网!
相关文章
- 蓝色星原旅谣配队一览 蓝色星原旅谣手游安卓手机版如何配队 09-08
- 蓝色星原旅谣奇波强度排名一览 蓝色星原旅谣手游安卓手机版奇波推荐 09-08
- 口袋斗罗大陆内置MOD修改器最新版下载 破解版内置菜单 09-08
- C#使用随机枢轴实现方式快速排序的做法实用指南 09-08
- c语言程序设计教程龚本灿适合怎么学 09-08
- c语言程序设计软件需要电脑配置 09-08