App下載

在html5中怎么使用localStorage中存儲對象?案例詳解!

猿友 2021-07-30 10:20:13 瀏覽數(shù) (2094)
反饋

在開發(fā)中我們需要將對象進行一個存儲的步驟,那么今晚小編就和大家討論一下有關于:“在html5中怎么使用localStorage中存儲對象?”這個問題,下面是小編整理的相關內(nèi)容分享,希望可以幫助到大家!

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

我可以使用來存儲和檢索原始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方法是在存儲輸入之前將輸入轉(zhuǎn)換為字符串。

解決方案:

再次查看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中存儲對象”這方面的相關內(nèi)容也有了不少的了解,對于html5這方面有感興趣的小伙伴們都可以在W3Cschool中進行個系統(tǒng)的學習! 


0 人點贊