如何在 HTML5 localStorage 中存储对象?
技术问答
352 人阅读
|
0 人回复
|
2023-09-11
|
我想在 HTML在5 中储存一个 JavaScript 对象localStorage,但我的对象显然被转换成字符串。, ~+ \2 U; |) n; ?8 T) a4 o0 \
我可以使用 存储和检索原始 JavaScript 类型和数组localStorage,但对象似乎不起作用。他们应该吗?
. F" E# l& Q. e/ O/ _# k1 c2 r这是我的代码:/ D8 m3 g- C( Y q
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 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);. P5 W4 P( Y) f; o# G& V4 @
控制台输出是
0 V/ b* D8 T3 Z4 K3 J1 F/ Ctypeof testObject: objecttestObject properties: one: 1 two: 2 three: 3typeof retrievedObject: stringValue of retrievedObject: [object Object]
3 @4 N' A5 B" b/ S! k2 a 在我看来,应该setItem该方法是在存储前将输入转换为字符串。
& d4 V' l: e, ^; `% l C/ G我在 Safari、Chrome 和 Firefox 我看到了这种行为,所以我想这是我对的HTML5 Web Storage对规范的误解,而不是浏览器的错误或限制。
9 x; M! E" N9 S& b: m) F我试图理解http://www.w3.org/TR/html5/infrastructure.html中描述的结构化克隆算法。我不完全理解它在说什么,但也许我的问题与我对象的属性有关(?2 e, p: l+ o3 A9 } D
有没有简单的解决方案?. V3 d- z/ S: t# a5 ~& _' Z8 s
更新:W3C 最终改变了对结构化克隆规范的看法,并决定改变规范以匹配实现。https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111。所以这个问题不再是 100% 有效,但答案可能仍然有趣。
5 A# c* \! P) X c5 G# Z 5 w$ Q" f& S1 l9 L1 J& I% b5 k
解决方案: 2 n$ S6 n: {7 k1 ]: R+ ?6 u9 s F
再次查看Apple、Mozilla和Mozilla该功能似乎仅限于处理字符串键/值对。 ]# _) i* g) K
解决方案是在存储对象之前对其进行处理字符串化,然后在检索过程中进行分析:7 u" P' q8 L7 u; Z! j- |) Q; G
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));* {- N; f- H% Z! x0 E3 ?' L
|
|
|
|
|
|