App下載

在html5中怎么使用localStorage中存儲(chǔ)對(duì)象?案例詳解!

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

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

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

我可以使用來存儲(chǔ)和檢索原始JavaScript類型和數(shù)組localStorage,但是對(duì)象似乎無法正常工作。應(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);

控制臺(tái)輸出為

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

在我看來,該setItem方法是在存儲(chǔ)輸入之前將輸入轉(zhuǎn)換為字符串。

解決方案:

再次查看Apple,Mozilla和Mozilla文檔,該功能似乎僅限于處理字符串鍵/值對(duì)。

一種解決方法是在存儲(chǔ)對(duì)象之前先對(duì)它進(jìn)行字符串化處理,然后在檢索它時(shí)對(duì)其進(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));

通過改文章的分享相信很多小伙伴們對(duì)于:“在html5中怎么使用localStorage中存儲(chǔ)對(duì)象”這方面的相關(guān)內(nèi)容也有了不少的了解,對(duì)于html5這方面有感興趣的小伙伴們都可以在W3Cschool中進(jìn)行個(gè)系統(tǒng)的學(xué)習(xí)! 


0 人點(diǎn)贊