一给郊、兼容性:如果不考慮ie6、7捧灰、8淆九,請(qǐng)盡情使用
二、使用方法:
- 判斷瀏覽器是否支持localStorage
if (!window.localStorage) {
console.log('您的瀏覽器不支持localStorage');
} else {
console.log('您的瀏覽器非常給力');
}
- 寫(xiě)入數(shù)據(jù)
var storage = window.localStorage;
storage.setItem("a", 123);
storage.setItem("b", 345);
//此處有陷阱毛俏,請(qǐng)繼續(xù)往下看
- 讀取數(shù)據(jù)
var a = storage.getItem("a");
console.log(a); //123
console.log(typeof a); //string
注意:
我們存儲(chǔ)時(shí)候的值為number類(lèi)型炭庙,獲取后為string類(lèi)型
說(shuō)明localStorage只以字符串形式進(jìn)行存儲(chǔ)
所以在存儲(chǔ)之前,請(qǐng)將存儲(chǔ)數(shù)據(jù)轉(zhuǎn)換成string類(lèi)型
- 獲取鍵(key)
for (var i = 0; i < storage.length; i++) {
var key = storage.key(i);
console.log(key);
}
- 刪除數(shù)據(jù)
storage.removeItem('a'); //刪除a字段的數(shù)據(jù)
storage.clear(); //刪除所有數(shù)據(jù)
console.log(storage); // ''