localStorage的读取
if(!window.localStorage){alert("浏览器支持localstorage");
}else{var storage=window.localStorage;storage["a"]=1;storage.b=2;storage.setItem("c",3);console.log(typeof storage["a"]);console.log(typeof storage["b"]); console.log(typeof storage["c"]); var a=storage.a;console.log(a); var b=storage["b"];console.log(b); var c=storage.getItem("c");console.log(c);
}
localStorage的删除
将localStorage的所有内容清除
var storage=window.localStorage;
storage.a=1;
storage.setItem("c",3);
console.log(storage);
storage.clear();
console.log(storage);
将localStorage中的某个键值对删除
var storage=window.localStorage;
storage.a=1;
storage.setItem("c",3);
console.log(storage);
storage.removeItem("a");
console.log(storage.a);
控制台输出
localStorage的键获取
var storage=window.localStorage;
storage.a=1;
storage.setItem("c",3);
for(var i&#61;0;i<storage.length;i&#43;&#43;){var key&#61;storage.key(i);console.log(key);
}
一般我们会将JSON存入localStorage中&#xff0c;但是在localStorage会自动将localStorage转换成为字符串形式
这个时候我们可以使用JSON.stringify()这个方法&#xff0c;来将JSON转换成为JSON字符串
if(!window.localStorage){alert("浏览器支持localstorage");
}else{var storage&#61;window.localStorage;var data&#61;{name:&#39;xiecanyong&#39;,sex:&#39;man&#39;,hobby:&#39;program&#39;};var d&#61;JSON.stringify(data);storage.setItem("data",d);console.log(storage.data);
}
读取之后要将JSON字符串转换成为JSON对象&#xff0c;使用JSON.parse()方法
var storage&#61;window.localStorage;
var data&#61;{name:&#39;xiecanyong&#39;,sex:&#39;man&#39;,hobby:&#39;program&#39;
};
var d&#61;JSON.stringify(data);
storage.setItem("data",d);
var json&#61;storage.getItem("data");
var jsonObj&#61;JSON.parse(json);
console.log(typeof jsonObj);