在HTML5 localStorage中存儲對象 - Storing Objects in HTML5 localStorage

問題:

I'd like to store a JavaScript object in HTML5 localStorage , but my object is apparently being converted to a string. 我想將JavaScript對象存儲在HTML5 localStorage ,可是個人對象顯然正在轉換爲字符串。 html

I can store and retrieve primitive JavaScript types and arrays using localStorage , but objects don't seem to work. 我能夠使用localStorage存儲和檢索原始JavaScript類型和數組,可是對象彷佛沒法正常工做。 Should they? 應該嗎 html5

Here's my code: 這是個人代碼: web

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);

The console output is 控制檯輸出爲 算法

typeof testObject: object
testObject properties:
  one: 1
  two: 2
  three: 3
typeof retrievedObject: string
Value of retrievedObject: [object Object]

It looks to me like the setItem method is converting the input to a string before storing it. 在我看來, setItem方法在存儲輸入以前將輸入轉換爲字符串。 數組

I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the HTML5 Web Storage spec, not a browser-specific bug or limitation. 我在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 . 我試圖弄清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 (???) 我不徹底明白這是什麼意思,但也許個人問題與個人對象的屬性不可枚舉有關(???) app

Is there an easy workaround? 有一個簡單的解決方法嗎? ide


Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. 更新:W3C最終改變了對結構化克隆規範的想法,並決定更改規範以匹配實現。 See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111 . 參見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. 所以,此問題再也不100%有效,但答案可能仍然頗有趣。 this


解決方案:

參考一: https://stackoom.com/question/8R7k/在HTML-localStorage中存儲對象
參考二: https://oldbug.net/q/8R7k/Storing-Objects-in-HTML5-localStorage
相關文章
相關標籤/搜索