我想在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存储规范的误解,而不是浏览器特定的错误或限制。
I've tried to make sense of the structured clone algorithm described in 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. See 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.
要存储对象,您可以写一个字母,用它来将对象从字符串传送到对象(可能没有意义)。例如
如果您使用用于拆分对象的字母,此技术将引起一些故障,这也是非常实验性的。