最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How will I use localStorage with Object - Stack Overflow

programmeradmin2浏览0评论

Please can someone make it clear why i need to do JSON.stringify(localStorage.setItem('data')); and then use JSON.parse(localStorage.getItem('data')) before i can get back my data object.

Please can someone make it clear why i need to do JSON.stringify(localStorage.setItem('data')); and then use JSON.parse(localStorage.getItem('data')) before i can get back my data object.

Share Improve this question asked Jul 18, 2017 at 8:57 LekensLekens 1,97720 silver badges33 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

In short: Because local storage can only store strings.

The longer answer is that Objects are plex data structures which, under the hood, consist of references to different parts of the puter's memory. You can't just dump them to a storage area because the data won't exist at those parts of the memory when you read the data back.

Thus you need to serialise the data somehow.

The localStorage API could have been written to do this automatically, but only under some circumstances. It wasn't, you have to do it manually, which means you are forced to know what you are doing so that (a) if you lose data it isn't due to the localStorage API being weird and mysterious and (b) you can choose between being memory efficient (localStorage gives you limited space) and being simple (just using JSON.stringify).

Go to developer tools (f12 in browser) -> Application > Locat Storage -> Any page here.

You can see that all the items here are just strings. If you want to store an object in the Local Storage, you need to convert it to string (JSON.stringify), and when you want to use your object again, you have to convert it back to an object (JSON.parse)

Local storage is made for storing strings as key value pairs. You can store an object by serialising it as a string, e.g.,

var object = {name:'somename'}
var string = JSON.stringify(object); // serialise as string
localStorage.setItem("name", string); // save string
var name = localStorage.getItem("name"); // for retrieving as string
var retrievedObj = JSON.parse(name) // for parse into object

LocalStorage saves data in the form of strings. If you save an object it will save as '[object Object]' because LocalStorage will call .toString() on the object.

发布评论

评论列表(0)

  1. 暂无评论