5月27日 01:05

What APIs Does the localStorage Object Have?

LocalStorage is part of the Web Storage API, which enables web pages to store data locally within the user's browser. Below are the commonly used API methods for the LocalStorage object:

  1. setItem(key, value): This method stores data in LocalStorage. It accepts two parameters: key (the name of the stored data) and value (the actual data to store). For example:
javascript
localStorage.setItem('username', 'JohnDoe');
  1. getItem(key): This method retrieves the value stored in LocalStorage using the specified key. If the key does not exist, it returns null. For example:
javascript
let userName = localStorage.getItem('username'); console.log(userName); // Output: JohnDoe
  1. removeItem(key): This method removes the data associated with the specified key from LocalStorage. For example:
javascript
localStorage.removeItem('username');
  1. clear(): This method clears all data from LocalStorage. For example:
javascript
localStorage.clear();
  1. length: A read-only property that returns the number of data items stored in LocalStorage. For example:
javascript
let numberOfItems = localStorage.length; console.log(numberOfItems);
  1. key(index): This method retrieves the key from LocalStorage based on the index. Indices start from 0. If the index is out of range, it returns null. For example:
javascript
let firstKeyName = localStorage.key(0); console.log(firstKeyName);

Data stored in LocalStorage is always in string format, even when storing numbers or objects. To store objects, it's common to use the JSON.stringify method to convert the object to a string, and then use JSON.parse to convert it back upon retrieval. For example:

javascript
let user = { name: 'John', age: 30 }; localStorage.setItem('user', JSON.stringify(user)); let retrievedUser = JSON.parse(localStorage.getItem('user')); console.log(retrievedUser); // Output: { name: 'John', age: 30 }

These are the main APIs of the LocalStorage object. It's important to note that while LocalStorage provides a convenient mechanism for local storage, it is not suitable for storing sensitive information because the data is stored in plain text and has no expiration time, making it vulnerable to cross-site scripting (XSS) attacks.

标签:JavaScript前端