在HTML5 localStorage中存储对象

我是研究僧i 提交于 2020-03-27 08:58:59

3 月,跳不动了?>>>

问题:

I'd like to store a JavaScript object in HTML5 localStorage , but my object is apparently being converted to a string. 我想将JavaScript对象存储在HTML5 localStorage ,但是我的对象显然正在转换为字符串。

I can store and retrieve primitive JavaScript types and arrays using localStorage , but objects don't seem to work. 我可以使用localStorage存储和检索原始JavaScript类型和数组,但是对象似乎无法正常工作。 Should they? 应该吗

Here's my code: 这是我的代码:

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

The console output is 控制台输出为

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

It looks to me like the setItem method is converting the input to a string before storing it. 在我看来, setItem方法在存储输入之前将输入转换为字符串。

I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the HTML5 Web Storage spec, not a browser-specific bug or limitation. 我在Safari,Chrome和Firefox中看到了这种行为,因此我认为这是我对HTML5 Web存储规范的误解,而不是浏览器特定的错误或限制。

I've tried to make sense of the structured clone algorithm described in http://www.w3.org/TR/html5/infrastructure.html . 我试图弄清http://www.w3.org/TR/html5/infrastructure.html中描述的结构化克隆算法。 I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???) 我不完全明白这是什么意思,但也许我的问题与我的对象的属性不可枚举有关(???)

Is there an easy workaround? 有一个简单的解决方法吗?


Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. 更新:W3C最终改变了对结构化克隆规范的想法,并决定更改规范以匹配实现。 See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 . 参见https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 So this question is no longer 100% valid, but the answers still may be of interest. 因此,此问题不再100%有效,但答案可能仍然很有趣。


解决方案:

参考一: https://stackoom.com/question/8R7k/在HTML-localStorage中存储对象
参考二: https://oldbug.net/q/8R7k/Storing-Objects-in-HTML5-localStorage
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!