乐闻世界logo
搜索文章和话题

How to store objects in html5 localstorage sessionstorage

1个答案

1

In HTML5, localStorage and sessionStorage can be used to store key-value pairs in the user's browser. The primary distinction between them lies in data persistence and scope:

  • Data stored in localStorage persists long-term until explicitly cleared, remaining intact even after the browser is closed.
  • Data stored in sessionStorage is valid only during the current browser session and is automatically cleared when the browser tab or window is closed.

However, it's important to note that localStorage and sessionStorage can only directly store strings. To store objects, you must first convert them into a JSON string format.

Here are the steps to store objects:

  1. First, create an object.
  2. Use the JSON.stringify() method to convert the object into a JSON string.
  3. Use localStorage.setItem() or sessionStorage.setItem() to store the string.

Here is a specific example:

javascript
// Assume we have an object to store var user = { name: "Zhang San", age: 30 }; // Convert the object to a JSON string var userString = JSON.stringify(user); // Store in localStorage localStorage.setItem('user', userString); // Store in sessionStorage sessionStorage.setItem('user', userString);

When reading stored objects, follow these steps:

  1. Use localStorage.getItem() or sessionStorage.getItem() to retrieve the stored string.
  2. Use JSON.parse() to convert the JSON string back into an object.

Here is an example of reading stored objects:

javascript
// Retrieve the string from localStorage var storedUserString = localStorage.getItem('user'); // Convert the string back to an object var storedUser = JSON.parse(storedUserString); // Now storedUser is the previously stored object console.log(storedUser.name); // Outputs: "Zhang San"

The same steps apply to sessionStorage.

In summary, when using the HTML5 Web Storage API to store objects, you must first convert the object into a string for storage, and then convert the string back to an object when reading. This ensures the object's structure and data remain preserved throughout the storage process.

2024年6月29日 12:07 回复

你的答案