如何在 HTML5 localStorage 中存储对象?
技术问答
271 人阅读
|
0 人回复
|
2023-09-11
|
我想在 HTML在5 中储存一个 JavaScript 对象localStorage,但我的对象显然被转换成字符串。
' q% |' V( q% e! {0 p1 r. G我可以使用 存储和检索原始 JavaScript 类型和数组localStorage,但对象似乎不起作用。他们应该吗?
- P; s- |9 H- j+ o# M1 m这是我的代码:
$ x% L% q# i }: Pvar 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 storagelocalStorage.setItem('testObject',testObject);// Retrieve the object from storagevar retrievedObject = localStorage.getItem('testObject');console.log('typeof retrievedObject: ' typeof retrievedObject);console.log('Value of retrievedObject: ' retrievedObject);
/ `' S% D: s/ {! c" K1 r3 J, K5 q 控制台输出是
2 W; r- D& ~( V9 E/ ?$ ntypeof testObject: objecttestObject properties: one: 1 two: 2 three: 3typeof retrievedObject: stringValue of retrievedObject: [object Object]) Z; a, G$ X; T; N1 o2 t% w4 O
在我看来,应该setItem该方法是在存储前将输入转换为字符串。
( o' } h3 U; w5 d3 v8 W我在 Safari、Chrome 和 Firefox 我看到了这种行为,所以我想这是我对的HTML5 Web Storage对规范的误解,而不是浏览器的错误或限制。
8 f& i, S4 w. c4 i5 l0 I0 p我试图理解http://www.w3.org/TR/html5/infrastructure.html中描述的结构化克隆算法。我不完全理解它在说什么,但也许我的问题与我对象的属性有关(?( z3 o5 G8 ?9 M8 }& r6 W; q
有没有简单的解决方案?! v) y+ r# p: D$ r
更新:W3C 最终改变了对结构化克隆规范的看法,并决定改变规范以匹配实现。https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111。所以这个问题不再是 100% 有效,但答案可能仍然有趣。7 x& k/ b. W( S0 O% S" @
5 t6 r- g$ |) T) s( u: I
解决方案:
- M2 F& ]$ e3 a3 c: V I/ b. c 再次查看Apple、Mozilla和Mozilla该功能似乎仅限于处理字符串键/值对。4 i4 ? l0 [, p
解决方案是在存储对象之前对其进行处理字符串化,然后在检索过程中进行分析:1 _% E! O4 V5 F
var testObject = { 'one': 1,'two': 2,'three 3 }Put the object into storagelocalStorage.setItem('testObject',JSON.stringify(testObject));// Retrieve the object from storagevar retrievedObject = localStorage.getItem('testObject');console.log('retrievedObject: ',JSON.parse(retrievedObject));
, X/ H0 O- q' A# `4 \0 Q1 t |
|
|
|
|
|