我想在HTML5中存儲一個(gè)JavaScript對象localStorage
,但是我的對象顯然正在轉(zhuǎn)換為字符串。
我可以使用來存儲和檢索原始JavaScript類型和數(shù)組localStorage
,但是對象似乎無法正常工作。應(yīng)該嗎
這是我的代碼:
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
方法是在存儲輸入之前將輸入轉(zhuǎn)換為字符串。
再次查看Apple,Mozilla和Mozilla文檔,該功能似乎僅限于處理字符串鍵/值對。
一種解決方法是在存儲對象之前先對它進(jìn)行字符串化處理,然后在檢索它時(shí)對其進(jìn)行解析:
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));
到此這篇關(guān)于在HTML5 localStorage中存儲對象的文章就介紹到這了,更多相關(guān)HTML5 localStorage存儲對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!
標(biāo)簽:營口 晉中 河池 眉山 崇左 北海 阜陽 青海
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《在HTML5 localStorage中存儲對象的示例代碼》,本文關(guān)鍵詞 在,HTML5,localStorage,中,存儲,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。