Start with an interview question

LocalStorage and sessionStorage localStorage and sessionStorage We can understand the difference between the two, let’s look at it together next!

I met sessionStorage

SessionStorage (Key, Value); sessionStorage (Key, Value); sessionStorage (Key, Value);

How to use

const person = { 
  name: 'huangyanting',
  age: 3 
}
sessionStorage.setItem('tg',person)

sessionStorage.getItem('tg')  // '[object Object]'
Copy the code

In SessionStorage, the Value of tg is [Object Object]. In SessionStorage, the Value of TG is [object object]. Of course, this is not what we expected, so how do we get the data we want?

sessionStorage.setItem('tg',JSON.stringify(person))
Copy the code

Now, obviously, we’ve met our expectations, so let’s try to pull out the data and see

const result = sessionStorage.getItem('tg')
// '{"name":"huangyanting","age":3}'

Object.prototype.toString.call(result)  
// '[object String]'
Copy the code

We’re fetching a string, and that’s not what we want, so what do we do?

const changeResult = JSON.parse(sessionStorage.getItem('tg'))
// {name: 'huangyanting', age: 3}

Object.prototype.toString.call(changeResult)
//'[object Object]'
Copy the code

Thus, it can be seen that by converting it into a string and then converting it into an object when it is taken out, it can be stored and read normally.

Memory size

SessionStorage: How much memory does sessionStorage have?

The online test

From the picture above, we can getlocalStorageandsessionStorageThe storage space is 5101K, equal to 4.98M

The failure time

The expiry time of sessionStorage is whether the current session is closed or not. If there are keys and values stored in the current session, the session closing data will disappear. Therefore, we can conclude that the expiry of sessionStorage depends on the session

The expiration time of localStorage is manually deleted, which is different from that of sessionStorage

localStorage.setItem('tg',' = =')
Copy the code

When we need to remove, but it should be noted that when we use localStorage, remove, store and remove methods are the same as sessionStorage

localStorage.removeItem('tg')
Copy the code

Usage scenarios

In our daily development, we can use sessionStorage and localStorage according to business scenarios, considering the size of storage space, of course, we can not abuse, shortcomings also please correct ~