程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

在HTML5 localStorage中存储对象

发布于2021-01-31 17:06     阅读(754)     评论(0)     点赞(0)     收藏(4)


我想在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方法是在存储之前将输入转换为字符串。

我在Safari,Chrome和Firefox中看到了这种行为,因此我认为这是我对HTML5 Web存储规范的误解,而不是浏览器特定的错误或限制。

我试图弄清http://www.w3.org/TR/html5/infrastructure.html中描述结构化克隆算法我不完全明白这是什么意思,但也许我的问题与我的对象的属性不可枚举有关(???)

有一个简单的解决方法吗?


更新:W3C最终改变了对结构化克隆规范的想法,并决定更改规范以匹配实现。参见https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111因此,此问题不再100%有效,但是答案可能仍然很有趣。


解决方案


再次查看AppleMozillaMozilla文档,该功能似乎仅限于处理字符串键/值对。

一种解决方法是在存储对象之前先对其进行字符串化,然后在检索它时对其进行解析:

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));



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.qianduanheidong.com/blog/article/118/1aa19fca3aee07957fde/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

0 0
收藏该文
已收藏

评论内容:(最多支持255个字符)