if(window.localStorage){
//检查浏览器是否支持localStorage
localStorage['book'] = "xxxxx"; //存储值的两种方式
localStorage.setItem("author","xxxx");
//读取值的三种方式
console.log(localStorage.getItem("book"));
console.log(localStorage.author);
console.log(localStorage["author"]);
//删除值的三种方式
delete localStorage['author']; //undefined
localStorage.removeItem('author'); //null
localStorage.clear(); //删除所有的key
}
注释:localStorage只能够存储字符串,若试图存储其他数据,会被强制转换成字符串
如果要存储JSON对象,可以使用stringify和parse方法对JSON数据进行序列化和反序列化
例子:
var author = {
'name' : 'xxx'
}
localStorage['author'] = JSON.stringify(author);
console.log(JSON.parse(localStorage['author']).name);
属性:
setItem设置一个key
getItem获取一个key
removeItem移除一个key
length访问Storage对象中item的数量
key(n)访问第n个key的名称
clear清除所有内容
localStorage['book'] = "xxxxx"; //存储值的两种方式
localStorage.setItem("author","xxxx");
//读取值的三种方式
console.log(localStorage.getItem("book"));
console.log(localStorage.author);
console.log(localStorage["author"]);
//删除值的三种方式
delete localStorage['author']; //undefined
localStorage.removeItem('author'); //null
localStorage.clear(); //删除所有的key
}
注释:localStorage只能够存储字符串,若试图存储其他数据,会被强制转换成字符串
如果要存储JSON对象,可以使用stringify和parse方法对JSON数据进行序列化和反序列化
例子:
var author = {
'name' : 'xxx'
}
localStorage['author'] = JSON.stringify(author);
console.log(JSON.parse(localStorage['author']).name);
属性:
setItem设置一个key
getItem获取一个key
removeItem移除一个key
length访问Storage对象中item的数量
key(n)访问第n个key的名称
clear清除所有内容