主頁 > 知識庫 > 在HTML5 localStorage中存儲對象的示例代碼

在HTML5 localStorage中存儲對象的示例代碼

熱門標簽:智能語音電銷機器人客戶端 江西ai電銷機器人如何 威海語音外呼系統(tǒng)平臺 地圖標注員工作內容 西安金倫外呼系統(tǒng) 通遼地圖標注app 中國地圖標注城市的 高德地圖標注廁所 地圖標注沿海城市房價

我想在HTML5中存儲一個JavaScript對象localStorage,但是我的對象顯然正在轉換為字符串。

我可以使用來存儲和檢索原始JavaScript類型和數(shù)組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方法是在存儲輸入之前將輸入轉換為字符串。

解決方案:

再次查看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));

到此這篇關于在HTML5 localStorage中存儲對象的文章就介紹到這了,更多相關HTML5 localStorage存儲對象內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持腳本之家!

標簽:營口 晉中 河池 眉山 崇左 北海 阜陽 青海

巨人網(wǎng)絡通訊聲明:本文標題《在HTML5 localStorage中存儲對象的示例代碼》,本文關鍵詞  在,HTML5,localStorage,中,存儲,;如發(fā)現(xiàn)本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《在HTML5 localStorage中存儲對象的示例代碼》相關的同類信息!
  • 本頁收集關于在HTML5 localStorage中存儲對象的示例代碼的相關信息資訊供網(wǎng)民參考!
  • 推薦文章