iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 11
0
Modern Web

從Stack Overflow學前端系列 第 11

從StackOverflow上學CODING(11)網頁localStrorage的存取

  • 分享至 

  • xImage
  •  

Storing Objects in HTML5 localStorage

I'd like to store a JavaScript object in HTML5 localStorage, but my object is apparently being converted to a string.
我想要存一個js物件到localStorage內,但是我的物件好像被轉換成了字串
I can store and retrieve primitive JavaScript types and arrays using localStorage, but objects don't seem to work. Should they?
我現在有辦法用localStorage分別存、取js類別與陣列,但是卻沒有辦法存取物件,這是可行的嗎?

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);

The console output is
console輸出

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

It looks to me like the setItem method is converting the input to a string before storing it.
我的看法是setItem這個方法在存之前把input轉換為一個字串
I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the HTML5 Web Storage spec, not a browser-specific bug or limitation.
我在Safari, Chrome, and Firefox都看到了這個舉動,所以我猜大概是我誤會了哪些地方而不是瀏覽器問題
I've tried to make sense of the structured clone algorithm described in http://www.w3.org/TR/html5/infrastructure.html. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???)
Is there an easy workaround?
即便了我參考了這個網址我還是不太理解他在說甚麼,可以為我詳解下嗎


Looking at the Apple, Mozilla and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.
在看了Apple, Mozilla文件後,似乎的確只能轉換string與value
A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:
不過另一個方法可以先字串話你的物件然後再儲存,然後在取出時parse:

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));

上一篇
從StackOverflow上學CODING(10)如何清空陣列
下一篇
從StackOverflow上學CODING(12)與jQuey 的$(document).ready 相同的語法
系列文
從Stack Overflow學前端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言