页面传值不交互:JS存储数据之LocalStorage用法

来源:互联网 发布:java做游戏 编辑:程序博客网 时间:2024/06/05 23:55

本人的需求是一个页面传值给另外一个页面,但是不需要交互:

A页面设置LocalStorage:
    if(!window.localStorage){
            alert("浏览器不支持localstorage");
     }else{
            var storage=window.localStorage;
            localStorage.setItem("name",APP_USERNAME) ;
//存储名字为name值为APP_USERNAME的变量

    localStorage.name = APP_USERNAME; // 等价于上面的命令

        }

B页面获取name值:
   
var storage=window.localStorage;
     //第一种方法读取
     var name=localStorage.getItem("name");读取保存在localStorage对象里名为name的变量的值。


一些常用的API如下表所示:

名称作用clear清空localStorage上存储的数据getItem读取数据hasOwnProperty检查localStorage上是否保存了变量x,需要传入xkey读取第i个数据的名字或称为键值(从0开始计数)lengthlocalStorage存储变量的个数propertyIsEnumerable用来检测属性是否属于某个对象的removeItem删除某个具体变量setItem存储数据toLocaleString将(数组)转为本地字符串valueOf获取所有存储的数据


其他操作:

清空localStorage

localStorage.clear()    // undefined    localStorage            // Storage {length: 0}

存储数据

localStorage.setItem("name","caibin") //存储名字为name值为caibin的变量localStorage.name = "caibin"; // 等价于上面的命令localStorage // Storage {name: "caibin", length: 1}

读取数据

localStorage.getItem("name") //caibin,读取保存在localStorage对象里名为name的变量的值localStorage.name // "caibin"localStorage.valueOf() //读取存储在localStorage上的所有数据localStorage.key(0) // 读取第一条数据的变量名(键值)//遍历并输出localStorage里存储的名字和值for(var i=0; i<localStorage.length;i++){    console.log('localStorage里存储的第'+i+'条数据的名字为:'+localStorage.key(i)+',值为:'+localStorage.getItem(localStorage.key(i)));}

删除某个变量

localStorage.removeItem("name"); //undefinedlocalStorage // Storage {length: 0} 可以看到之前保存的name变量已经从localStorage里删除了

检查localStorage里是否保存某个变量

// 这些数据都是测试的,是在我当下环境里的,只是demo哦~localStorage.hasOwnProperty('name') // truelocalStorage.hasOwnProperty('sex')  // false

将数组转为本地字符串

var arr = ['aa','bb','cc']; // ["aa","bb","cc"]localStorage.arr = arr //["aa","bb","cc"]localStorage.arr.toLocaleString(); // "aa,bb,cc"

将JSON存储到localStorage里

var students = {    xiaomin: {        name: "xiaoming",        grade: 1    },    teemo: {        name: "teemo",        grade: 3    }}students = JSON.stringify(students);  //将JSON转为字符串存到变量里console.log(students);localStorage.setItem("students",students);//将变量存到localStorage里var newStudents = localStorage.getItem("students");newStudents = JSON.parse(students); //转为JSONconsole.log(newStudents); // 打印出原先对象





原创粉丝点击