I'd like to store a JavaScript object in HTML5 localStorage
, but my object is apparently being converted to a string. 我想将JavaScript对象存储在HTML5 localStorage
,可是个人对象显然正在转换为字符串。 html
I can store and retrieve primitive JavaScript types and arrays using localStorage
, but objects don't seem to work. 我能够使用localStorage
存储和检索原始JavaScript类型和数组,可是对象彷佛没法正常工做。 Should they? 应该吗 html5
Here's my code: 这是个人代码: web
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 (???) 我不彻底明白这是什么意思,但也许个人问题与个人对象的属性不可枚举有关(???) app
Is there an easy workaround? 有一个简单的解决方法吗? ide
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%有效,但答案可能仍然颇有趣。 this