local storage (localStorage)
storage
setItem
//键和值都是字符串
localStorage.setItem("stringKey","StringVal");
//即使存数字,也会转字符串
localStorage.setItem("num",666);
//存对象,默认调用objec的toString方法,无意义,可转化为json后再存储
const personObj = {
name:"张三",
age:18
}
localStorage.setItem("personObj",JSON.stringify(personObj));
Browser local storage space:
F12 observation
Obtain
getItem
var val;
val = localStorage.getItem("stringKey");
console.log("stringKey",val);
val = localStorage.getItem("num");
console.log("num",val);
val = localStorage.getItem("personObj");
console.log("personObj",val);
val = localStorage.getItem("不存在的key");
console.log("不存在的key",val);
Observe that if you get a key that does not exist, the result is null
delete one
localStorage.removeItem("stringKey");
clear all
localStorage.clear();
session storage (sessionStorage)
The calling method is exactly the same as localStorage, just replace localStorage in the above code with sessionStorage.
It is automatically cleared when the browser is closed