存储JS对象
<script type="text/javascript">
/*封装人员信息*/
function Person(id,name,age) {
this.id = id;
this.name = name;
this.age = age;
}
var p = new Person(1001,'tom',17);
document.write(p.id + ',' + p.name + ',' + p.age);
//把对象转换为JSON数据格式
var jsonStr = JSON.stringify(p);
//存储到localStorage
localStorage.person = jsonStr;
/*
* 或者是localStorage.setItem(key,value);
*/
</script>
读取JS对象
<script type="text/javascript">
//读取JSON字符串
var jsonStr = localStorage.person;
/*
* 或者是localStorage.getItem(key);
*/
if (jsonStr) {
// 把JSON字符串转换为对象
var jsonObj = JSON.parse(jsonStr);
document.write(jsonObj.id + ',' + jsonObj.name + ',' + jsonObj.age);
}
</script>