小编典典

在HTML5 localStorage中存储对象

html

我想在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中看到了这种行为,因此我认为这是我对HTML5Web存储规范的误解,而不是浏览器特定的错误或限制。

我试图弄清中描述的结构化克隆算法。我不完全理解这是什么意思,但也许我的问题与我的对象的属性不可枚举有关(???)

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


更新:W3C最终改变了对结构化克隆规范的想法,并决定更改该规范以匹配实现。因此,此问题不再100%有效,但答案可能仍然很有趣。


阅读 576

收藏
2020-05-10

共1个答案

小编典典

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

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

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));
2020-05-10