溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

html5中如何使用localStorage中存儲對象

發(fā)布時間:2022-02-21 09:53:50 來源:億速云 閱讀:204 作者:iii 欄目:開發(fā)技術

本文小編為大家詳細介紹“html5中如何使用localStorage中存儲對象”,內容詳細,步驟清晰,細節(jié)處理妥當,希望這篇“html5中如何使用localStorage中存儲對象”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

我想在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中存儲對象”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI