js browser storage webStorage
The browser implements the local storage mechanism through the Window.sessionStorage and Window.localStorage properties
Related APIs:
The APIs of sessionStorage and localStorage are the same
- xxxxxStorage.setItem('key','value');
This method accepts a key and value as parameters, and will add the key-value pair to the storage. If the key name exists, update its corresponding value - xxxxxStorage.getItem('key');
This method accepts a key name as a parameter and returns the value corresponding to the key name - xxxxxStorage.removeItem('key');
This method accepts a key name as a parameter and deletes the key name from the storage - xxxxxStorage.clear();
This method will clear all data in the storage
let p = {
name:'张三',age:18}
function saveData(){
localStorage.setItem('msg','hello');
localStorage.setItem('msg2',666); //666存储后为字符串
localStorage.setItem('person',JSON.stringify(p));
}
function readData(){
console.log(localStorage.getItem('msg'));
const result = localStorage.getItem('person');
console.log(JSON.parse(result));
}
function deleteData(){
localStorage.removeItem('msg2');
}
function deleteAllData(){
localStorage.clear();
}
- The content stored in sessionStorage will disappear when the browser window is closed
- The content stored in localStorage needs to be manually cleared before it disappears
- xxxxxStorage.getItem(xxx), if the value corresponding to xxx cannot be obtained, then the return value of getItem is null
- The result of JSON.parse(null) is still null