当前位置: 代码网 > it编程>网页制作>html5 > 在HTML5 localStorage中存储对象的示例代码

在HTML5 localStorage中存储对象的示例代码

2021年04月20日 html5 我要评论
在HTML5 localStorage中存储对象的示例代码这篇文章主要介绍了在HTML5 localStorage中存储对象的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 21-04-20

我想在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存储对象内容请搜索代码网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com