localStorage存储数据的格式

1. localStorage 是以字符串的形式来存储的

//存:转为字符串
    let obj = {"name":"Lee","age":"20"}
    localStorage.setItem("user",JSON.stringify(obj));

//取:转换成对象
    let user = JSON.parse(localStorage.getItem("user"))

//清空:
    localStorage.setItem("user","");

//删除:
    localStorage.remove("user");

2. localStorage 储存的数字类型会自动转为字符串类型

//声明数字类型
    let index = 1;
    console.log(typeof index); // number

//直接储存
    localStorage.setItem('currentPage', index);

//获取的是字符串类型
    let getIndex = localStorage.getItem('currentPage');
    console.log(getIndex); // 1
    console.log(typeof getIndex); // string

 

你可能感兴趣的:(localStorage存储数据的格式)