** // localStorage 把浏览器关闭掉,还会在**
** // sessionStorage 把浏览器关闭掉,就没了**
<button onClick="save()">保存</button>
<button onClick="read()">读取</button>
<button onClick="del()">删除</button>
<button onClick="clearAll()">清空</button>
<script>
function save(){
// 形式是键值对
// key 和 value 必须都是字符串
const msg='hello'
// window.localStorage.setItem('msg',msg)
const number=6
// window.localStorage.setItem('number',number) //msg 如果是number会把它转成字符串
const student={
name:'xiaohua',
age:19
}
console.log(student.toString()) // 一个对象调了toString方法 就长成 [Object,Object]
// 原因:如果第二个参数不是string类型,一定会帮你掉用toString();
// 错误的
window.localStorage.setItem('studentno',student) //msg [Object Object]
// 正确的
window.localStorage.setItem('student',JSON.stringify(student)) //msg "{"name":"xiaohua","age":19}"
// window.localStorage.setItem('msg',[3,41,5]) //msg 如果是number会把它转成字符串
// window.localStorage.setItem('msg',[{hello:'111'},{hello:'222'}]) //msg [object Object],[object Object]串
}
function read(){
const student=window.localStorage.getItem('student')
console.log('student@@2',student) //{"name":"xiaohua","age":19} //字符串
console.log('JSON.parse(student)@@@',JSON.parse(student)) //{name: 'xiaohua', age: 19} //对象
// 没有school和sun
// 如果没有的话,就是null
console.log(window.localStorage.getItem('school')) //null
const res=window.localStorage.getItem('sun')
console.log(JSON.parse(res)) //null
}
function del(){
window.localStorage.removeItem('student')
}
function clearAll(){
window.localStorage.clear()
}
</script>
localStorage
1:点了按钮,操作了api
2:用户主动的清空缓存,也会没