我想在HTML5 localStorage
中存储一个JavaScript对象,但是我的对象似乎被转换为了字符串。
我可以使用localStorage
来存储和检索原始的JavaScript类型和数组,但是对象似乎不起作用。它们应该吗?
这是我的代码:
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 Storage规范的误解,而不是浏览器特定的错误或限制。
我尝试理解描述在2 Common infrastructure的结构化克隆算法。我没有完全理解它的意思,但也许我的问题与我对象的属性不可枚举有关(???)。
有没有简单的解决方法?
更新:W3C最终改变了他们对结构化克隆规范的看法,并决定更改规范以匹配实现。请参见12111 - Storage对象getItem(key)方法的规范与实现行为不匹配 。因此,这个问题不再100%有效,但答案仍然可能会引起兴趣。